db.collection.findOneAndReplace()

在本页面

Definition

  • db.collection. findOneAndReplace(* filter replacement options *)
    • 3.2 版中的新功能。

根据指定的filter替换单个文档。

Syntax

findOneAndReplace()方法具有以下形式:

db.collection.findOneAndReplace(
   <filter>,
   <replacement>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnNewDocument: <boolean>,
     collation: <document>
   }
)

参数和选项

findOneAndReplace()方法采用以下参数和选项:

ParameterTypeDescription
filterdocument更新的选择标准。与find()方法中相同的query selectors可用。



指定一个空文档{ }来替换集合中返回的第一个文档。
如果未指定,则默认为空文档。
从 MongoDB 3.6.14(和 3.4.23)开始,如果查询参数不是文档,则操作错误。
| replacement |文档|替换文档。

不能包含update operators
<replacement>文档不能指定与替换文档不同的_id值。
| projection |文档|可选。要返回的字段子集。

要返回匹配文档中的所有字段,请省略此参数。
从 MongoDB 3.6.14(和 3.4.23)开始,如果 projection 参数不是文档,则操作错误。
| sort |文档|可选。指定与filter匹配的文档的排序 Sequences。

从 MongoDB 3.6.14(和 3.4.23)开始,如果 sort 参数不是文档,则操作错误。
See cursor.sort().|
| maxTimeMS |数字|可选。指定必须在其中完成操作的时间限制(以毫秒为单位)。如果超出限制,则会引发错误。
| upsert |布尔值|可选。当truefindOneAndReplace()之一时:

如果没有文档与filter匹配,则从replacement参数插入文档。插入新文档后返回null,除非returnNewDocumenttrue
将与filter匹配的文档替换为replacement文档。
如果在filterreplacement文档中均未指定,则 MongoDB 会将_id字段添加到替换文档中。如果两者中都存在_id,则值必须相等。
为避免多次更新,请确保query字段为uniquely indexed
默认为false
| returnNewDocument |布尔值|可选。当true时,返回替换文档而不是原始文档。

默认为false
|collation|document|Optional.

指定用于操作的collation
Collation允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则。
排序规则选项具有以下语法:
collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
指定排序规则时,locale字段为必填字段;所有其他排序规则字段都是可选的。有关字段的说明,请参见Collation Document
如果未指定排序规则,但是集合具有默认排序规则(请参见db.createCollection()),则该操作将使用为集合指定的排序规则。
如果没有为集合或操作指定排序规则,则 MongoDB 使用先前版本中使用的简单二进制比较进行字符串比较。
您不能为一个操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果对排序执行查找,则不能对查找使用一种排序规则,而对排序使用另一种排序规则。
3.4 版中的新功能。

Returns

返回原始文档,如果是returnNewDocument: true,则返回替换文档。

Behavior

findOneAndReplace()替换集合中与filter匹配的第一个匹配文档。 sort参数可用于影响修改哪个文档。

projection参数采用以下格式的文档:

{ field1 : < boolean >, field2 : < boolean> ... }

<boolean>值可以是以下任意值:

  • 1true以包括该字段。即使未在 projection 参数中明确声明_id字段,该方法也会返回_id字段。

  • 0false以排除该字段。可以在任何字段(包括_id)上使用。

Examples

替换文档

使用以下文档创建一个 samplesscores集合:

db.scores.insertMany([
   { "_id" : 1, "team" : "Fearful Mallards", "score" : 25000 },
   { "_id" : 2, "team" : "Tactful Mooses", "score" : 23500 },
   { "_id" : 3, "team" : "Aquatic Ponies", "score" : 19250 },
   { "_id" : 4, "team" : "Cuddly Zebras", "score" : 15235 },
   { "_id" : 5, "team" : "Garrulous Bears", "score" : 18000 }
]);

以下操作将查找score小于20000的文档并将其替换:

db.scores.findOneAndReplace(
   { "score" : { $lt : 20000 } },
   { "team" : "Observant Badgers", "score" : 20000 }
)

该操作返回已替换的原始文档:

{ "_id" : 3, "team" : "Aquatic Ponies", "score" : 19250 }

如果returnNewDocument为 true,则该操作将返回替换文档。

尽管多个文档符合过滤条件,但是db.collection.findOneAndReplace仅替换一个文档。

排序和替换文档

使用以下文档创建一个 samplesscores集合:

db.scores.insertMany([
   { "_id" : 1, "team" : "Fearful Mallards", "score" : 25000 },
   { "_id" : 2, "team" : "Tactful Mooses", "score" : 23500 },
   { "_id" : 3, "team" : "Aquatic Ponies", "score" : 19250 },
   { "_id" : 4, "team" : "Cuddly Zebras", "score" : 15235 },
   { "_id" : 5, "team" : "Garrulous Bears", "score" : 18000 }
]);

通过在score字段中包括升序的sort,以下示例替换了与filter匹配的文档中得分最低的文档:

db.scores.findOneAndReplace(
   { "score" : { $lt : 20000 } },
   { "team" : "Observant Badgers", "score" : 20000 },
   { sort: { "score" : 1 } }
)

该操作返回已替换的原始文档:

{ "_id" : 4, "team" : "Cuddly Zebras", "score" : 15235 }

有关此命令的未排序结果,请参见替换文件

return凭证中的项目特定字段

使用以下文档创建一个 samplesscores集合:

db.scores.insertMany([
   { "_id" : 1, "team" : "Fearful Mallards", "score" : 25000 },
   { "_id" : 2, "team" : "Tactful Mooses", "score" : 23500 },
   { "_id" : 3, "team" : "Aquatic Ponies", "score" : 19250 },
   { "_id" : 4, "team" : "Cuddly Zebras", "score" : 15235 },
   { "_id" : 5, "team" : "Garrulous Bears", "score" : 18000 }
])

以下操作使用projection仅在返回的文档中显示team字段:

db.scores.findOneAndReplace(
   { "score" : { $lt : 22250 } },
   { "team" : "Therapeutic Hamsters", "score" : 22250 },
   { sort : { "score" : 1 }, projection: { "_id" : 0, "team" : 1 } }
)

该操作仅返回team字段返回原始文档:

{ "team" : "Cuddly Zebras" }

用时间限制替换文档

以下操作将完成时间设置为 5 毫秒:

try {
   db.scores.findOneAndReplace(
      { "score" : { $gt : 25000 } },
      { "team" : "Emphatic Rhinos", "score" : 25010 },
      { maxTimeMS: 5 }
   );
} catch(e){
   print(e);
}

如果操作超过时间限制,则返回:

Error: findAndModifyFailed failed: { "ok" : 0, "errmsg" : "operation exceeded time limit", "code" : 50 }

用 Upsert 替换文档

如果没有文档与filter相匹配,以下操作将使用upsert字段插入替换文档:

try {
   db.scores.findOneAndReplace(
      { "team" : "Fortified Lobsters" },
      { "_id" : 6019, "team" : "Fortified Lobsters" , "score" : 32000},
      { upsert : true, returnNewDocument: true }
   );
} catch (e){
   print(e);
}

该操作返回以下内容:

{
   "_id" : 6019,
   "team" : "Fortified Lobsters",
   "score" : 32000
}

如果returnNewDocument为假,则该操作将返回null,因为没有原始文档要返回。

Specify Collation

3.4 版的新功能。

Collation允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则。

使用以下文档创建一个 samplesmyColl集合:

db.myColl.insertMany([
   { _id: 1, category: "café", status: "A" },
   { _id: 2, category: "cafe", status: "a" },
   { _id: 3, category: "cafE", status: "a" }
]);

以下操作包括collation选项:

db.myColl.findOneAndReplace(
   { category: "cafe", status: "a" },
   { category: "cafÉ", status: "Replaced" },
   { collation: { locale: "fr", strength: 1 } }
);

该操作返回以下文档:

{ "_id" : 1, "category" : "café", "status" : "A" }