On this page本页内容
db.collection.
findOneAndReplace
(filter, replacement, options)¶mongo
Shell Method
This page documents the 本页记录了mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. mongo
shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。
New in version 3.2.版本3.2中的新功能。
Replaces a single document based on the specified filter.根据指定的筛选器替换单个文档。
The findOneAndReplace()
method has the following form:findOneAndReplace()
方法的形式如下:
The findOneAndReplace()
method takes the following parameters and options:findOneAndReplace()
方法采用以下参数和选项:
filter | document |
|
replacement | document |
|
projection | document |
|
sort | document |
|
maxTimeMS |
number | |
upsert | boolean |
|
returnNewDocument | boolean |
|
collation | document |
|
Returns either the original document or, if returnNewDocument: true, the replacement document.返回原始文档,如果returnNewDocument:true
,则返回替换文档。
db.collection.findOneAndReplace()
replaces the first matching document in the collection that matches the 替换集合中与filter
. filter
匹配的第一个匹配文档。The sort
parameter can be used to influence which document is modified.sort
参数可用于影响修改的文档。
Language Consistency语言一致性
Starting in MongoDB 4.4, as part of making 从MongoDB 4.4开始,作为使find
and findAndModify
projection consistent with aggregation’s $project
stage,find
和findAndModify
投影与聚合的$project
阶段保持一致的一部分,
find
and findAndModify
projection can accept aggregation expressions and syntax.find
和findAndModify
投影可以接受聚合表达式和语法。The projection
parameter takes a document in the following form:projection
参数采用以下形式的文档:
<field>: <1 or true> |
|
<field>: <0 or false> |
|
"<field>.$": <1 or true> |
$ array projection operator, you can specify the projection to return the first element that match the query condition on the array field; e.g. "arrayField.$" : 1 . $ 数组投影运算符,可以指定投影以返回与数组字段上的查询条件匹配的第一个元素;例如,"arrayField.$" : 1 。 |
<field>: <array projection> |
$elemMatch , $slice , specifies the array element(s) to include, thereby excluding those elements that do not meet the expressions. $elemMatch ,$slice ,指定要包含的数组元素,从而排除那些不符合表达式的元素。 |
<field>: <aggregation expression> |
|
For fields in an embedded documents, you can specify the field using either:对于嵌入文档中的字段,可以使用以下任一方法指定字段:
"field.nestedfield": <value>
{ field: { nestedfield: <value> } }
(Starting in MongoDB 4.4)_id
The 默认情况下,_id
field is included in the returned documents by default unless you explicitly specify _id: 0
in the projection to suppress the field._id
字段包含在返回的文档中,除非在投影中明确指定_id: 0
以抑制该字段。
A projection
cannot contain both include and exclude specifications, with the exception of the _id
field:projection
不能同时包含包含和排除规范,但_id
字段除外:
_id
field is the only field that you can explicitly exclude._id
字段是唯一可以显式排除的字段。_id
field is the only field that you can explicitly include; however, the _id
field is included by default._id
字段是唯一可以显式包括的字段;但是,默认情况下会包含_id
字段。For more information on projection, see also:有关投影的更多信息,请参阅:
To use 要在分片集合上使用db.collection.findOneAndReplace()
on a sharded collection, the query filter must include an equality condition on the shard key.db.collection.findOneAndReplace()
,查询筛选器必须在分片键上包含相等条件。
Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 从4.4版开始,切分集合中的文档可能会缺少切分键字段。To target a document that is missing the shard key, you can use the 要将缺少切分键的文档作为目标,可以将null
equality match in conjunction with another filter condition (such as on the _id
field). null
相等匹配与另一个筛选条件结合使用(例如在_id
字段上)。For example:例如:
Starting in MongoDB 4.2, you can update a document’s shard key value unless the shard key field is the immutable 从MongoDB 4.2开始,可以更新文档的分片键值,除非分片键字段是不可变的_id
field. _id
字段。Before MongoDB 4.2, a document’s shard key field value is immutable.在MongoDB 4.2之前,文档的分片键字段值是不可变的。
Warning警告
Starting in version 4.4, documents in sharded collections can be missing the shard key fields. 从4.4版开始,分片集合中的文档可能会缺少分片键字段。Take precaution to avoid accidentally removing the shard key when changing a document’s shard key value.采取预防措施,以避免在更改文档的分片键值时意外删除分片键。
To modify the existing shard key value with 要使用db.collection.findOneAndReplace()
:db.collection.findOneAndReplace()
修改现有的碎片键值,请执行以下操作:
mongos
. mongos
上运行。Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 从4.4版开始,分片集合中的文档可能会缺少分片键字段。To use 要使用db.collection.findOneAndReplace()
to set the document’s missing shard key,db.collection.findOneAndReplace()
设置文档缺少的分片键,
mongos
. mongos
上运行。null
.null
,则必须在事务中或作为可重试写入运行。Tip
Since a missing key value is returned as part of a null equality match, to avoid updating a null-valued key, include additional query conditions (such as on the 由于缺少的键值是作为空相等匹配的一部分返回的,为了避免更新空值键值,请酌情包括其他查询条件(例如在_id
field) as appropriate._id
字段上)。
See also:
db.collection.findOneAndReplace()
can be used inside multi-document transactions.可以在多文档事务中使用。
Important
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,而多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
Starting in MongoDB 4.4 with feature compatibility version (fcv) 从功能兼容版本(fcv)"4.4"
, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction."4.4"
的MongoDB 4.4开始,如果事务不是跨切分写入事务,则可以在多文档事务中创建集合和索引。
As such, for the feature compatibility version (fcv) is 因此,对于功能兼容性版本(fcv)为"4.4"
or greater, db.collection.findOneAndReplace()
with upsert: true
can be run against an existing collection or a non-existing collection. "4.4"
或更高版本的情况,可以对现有集合或不存在的集合运行带有upsert:true
的db.collection.findOneAndReplace()
。If run against a non-existing collection, the operation creates the collection.如果针对不存在的集合运行,该操作将创建该集合。
If the feature compatibility version (fcv) is 如果功能兼容版本(fcv)为"4.2"
or less, the operation must be against an existing collection."4.2"
或更低,则操作必须针对现有集合。
Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注点。To use write concern with transactions, see Transactions and Write Concern.要将写关注点用于事务,请参阅事务和写关注点。
Create a sample 使用以下文档创建一个样本scores
collection with the following documents:scores
集合:
The following operation finds a document with 以下操作将查找score
less than 20000
and replaces it:scores
小于20000
的文档并将其替换:
The operation returns the original document that has been replaced:该操作将返回已替换的原始文档:
If returnNewDocument was true, the operation would return the replacement document instead.如果returnNewDocument
为true
,则操作将返回替换文档。
Although multiple documents meet the filter criteria, 虽然多个文档满足筛选条件,但db.collection.findOneAndReplace
replaces only one document.db.collection.findOneAndReplace
只替换一个文档。
Create a sample 使用以下文档创建一个样本scores
collection with the following documents:scores
集合:
By including an ascending sort on the 通过在score
field, the following example replaces the document with the lowest score among those documents that match the filter:score
字段中包含升序排序,以下示例将文档替换为与filter
匹配的文档中分数最低的文档:
The operation returns the original document that has been replaced:该操作将返回已替换的原始文档:
See Replace A Document for the non-sorted result of this command.有关此命令的未排序结果,请参阅替换文档。
Create a sample 使用以下文档创建一个样本scores
collection with the following documents:scores
集合:
The following operation uses projection to only display the 以下操作使用team
field in the returned document:projection
仅显示返回文档中的team
字段:
The operation returns the original document with only the 该操作返回原始文档,其中仅包含team
field:team
字段:
The following operation sets a 5ms time limit to complete:以下操作设置了5毫秒的完成时间限制:
If the operation exceeds the time limit, it returns:如果操作超过时间限制,则返回:
The following operation uses the upsert field to insert the replacement document if no document matches the filter:如果没有与filter
匹配的文档,以下操作将使用upsert
字段插入替换文档:
The operation returns the following:该操作返回以下内容:
If 如果returnNewDocument
was false, the operation would return null
as there is no original document to return.returnNewDocument
为false
,操作将返回null
,因为没有要返回的原始文档。
New in version 3.4.版本3.4中的新功能。
Collation排序规则 allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。
Create a sample 使用以下文档创建myColl
collection with the following documents:myColl
样本集合:
The following operation includes the collation option:以下操作包括排序规则选项:
The operation returns the following document:该操作将返回以下文档: