On this page本页内容
db.collection.
findOneAndUpdate
(filter, update, 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中的新功能。
Updates a single document based on the 根据filter
and sort
criteria.filter
和sort
条件更新单个文档。
The findOneAndUpdate()
method has the following form:findOneAndUpdate()
方法的形式如下:
The findOneAndUpdate()
method takes the following parameters:findOneAndUpdate()
方法采用以下参数:
filter |
document |
|
update |
document |
|
projection |
document |
|
sort |
document |
|
maxTimeMS |
number | |
upsert |
boolean |
|
returnNewDocument |
boolean |
|
collation |
document |
|
arrayFilters |
array |
Note
Note
|
returnNewDocument: true , the updated document.returnNewDocument:true ,则返回更新的文档。 |
db.collection.findOneAndUpdate()
updates the first matching document in the collection that matches the 更新集合中与filter
. filter
匹配的第一个匹配文档。The sort
parameter can be used to influence which document is updated.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
投影可以接受聚合表达式和语法。Projection Restrictions
for details.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>
{ field: { nestedfield: <value> } }
(Starting in MongoDB 4.4){ field: { nestedfield: <value> } }
(从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.findOneAndUpdate()
on a sharded collection, the query filter must include an equality condition on the shard key.
Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 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). For example:例如:
Starting in MongoDB 4.2, you can update a document’s shard key value unless the shard key field is the immutable _id
field. Before MongoDB 4.2, a document’s shard key field value is immutable.
Warning
Starting in version 4.4, documents in sharded collections can be missing the shard key fields. Take precaution to avoid accidentally removing the shard key when changing a document’s shard key value.从4.4版开始,分片集合中的文档可能会缺少分片键字段。采取预防措施,以避免在更改文档的shard key值时意外删除shard key。
To modify the existing shard key value with 要修改现有的db.collection.findOneAndUpdate()
:db.collection.findOneAndUpdate()
值
mongos
. Do not
issue the operation directly on the shard.Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. To use db.collection.findOneAndUpdate()
to set the document’s missing shard key,
mongos
. Do not
issue the operation directly on the shard.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.findOneAndUpdate()
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) "4.4"
, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.
As such, for the feature compatibility version (fcv) is "4.4"
or greater, db.collection.findOneAndUpdate()
with upsert: true
can be run against an existing collection or a non-existing collection. 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.要将写关注点用于事务,请参阅事务和写关注点。
In this section本节内容
arrayFilters
arrayFilters
执行数组更新操作The grades
collection contains documents similar to the following:grades
集合包含与以下类似的文档:
The following operation finds the first document where 下面的操作将查找第一个name : R. Stiles
and increments the score by 5
:name
为R. Stiles
的文档,并将score
增加5
:
The operation returns the original document before the update:操作将在更新之前返回原始文档:
If 如果returnNewDocument
was true, the operation would return the updated document instead.returnNewDocument
为true
,则操作将返回更新后的文档。
The grades
collection contains documents similar to the following:grades
集合包含与以下类似的文档:
The following operation updates a document where 以下操作将更新一个名为name : "A. MacDyver"
. name : "A. MacDyver"
的文档。The operation sorts the matching documents by 该操作按points
ascending to update the matching document with the least points.points
升序对匹配文档进行排序,以使用最少的点更新匹配文档。
The operation returns the original document before the update:操作将在更新之前返回原始文档:
The following operation uses projection to only display the _id
, points
, and assignment
fields in the returned document:
The operation returns the original document with only the fields specified in the projection
document and the _id
field as it was not explicitly suppressed (_id: 0
) in the projection document.
The following operation sets a 5ms time limit to complete the update:以下操作设置了5毫秒的时间限制以完成更新:
If the operation exceeds the time limit, it returns:如果操作超过时间限制,则返回:
The following operation uses the 如果没有与upsert
field to insert the update document if nothing 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.
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.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。
A collection myColl
has the following documents:myColl
集合包含以下文档:
The following operation includes the collation option:以下操作包括排序规则选项:
The operation returns the following document:该操作将返回以下文档:
arrayFilters
arrayFilters
执行阵列更新操作¶Note
arrayFilters
is not available for updates that use an aggregation pipeline.不适用于使用聚合管道的更新。
New in version 3.6.版本3.6中的新功能。
Starting in MongoDB 3.6, when updating an array field, you can specify 从MongoDB 3.6开始,在更新数组字段时,可以指定确定要更新哪些数组元素的arrayFilters
that determine which array elements to update.arrayFilters
。
arrayFilters
CriteriaarrayFilters
条件¶Note
arrayFilters
is not available for updates that use an aggregation pipeline.不适用于使用聚合管道的更新。
Create a collection 创建一个包含以下文档的集合:students
with the following documents:
To modify all elements that are greater than or equal to 100
in the grades
array, use the filtered positional operator $[<identifier>]
with the arrayFilters
option in the db.collection.findOneAndUpdate
method:
The operation updates the 该操作将更新单个文档的grades
field for a single document, and after the operation, the collection has the following documents:grades
字段,操作完成后,集合将包含以下文档:
Note
arrayFilters
is not available for updates that use an aggregation pipeline.不适用于使用聚合管道的更新。
Create a collection 使用以下文档创建students2
with the following documents:students2
集合:
The following operation finds a document where the _id
field equals 1
and uses the filtered positional operator $[<identifier>]
with the arrayFilters
to modify the mean
for all elements in the grades
array where the grade is greater than or equal to 85
.
The operation updates the 该操作将更新单个文档的grades
field for a single document, and after the operation, the collection has the following documents:grades
字段,操作完成后,集合将包含以下文档:
Starting in MongoDB 4.2, 从MongoDB 4.2开始,db.collection.findOneAndUpdate()
can accept an aggregation pipeline for the update. db.collection.findOneAndUpdate()
可以接受更新的聚合管道。The pipeline can consist of the following stages:管道可包括以下阶段:
$addFields
$set
$project
$unset
$replaceRoot
$replaceWith
Using the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).使用聚合管道可以实现更具表现力的update语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。
For example, create a collection 例如,使用以下文档创建students2
with the following documents:students2
集合:
The following operation finds a document where the 以下操作将查找_id
field equals 1
and uses an aggregation pipeline to calculate a new field total
from the grades
field:_id
字段等于1
的文档,并使用聚合管道从grades
字段计算新字段total
:
Note
The 管道中使用的$set
used in the pipeline refers to the aggregation stage $set
and not the update operator $set
.$set
指的是聚合阶段$set
,而不是更新运算符$set
。
The operation returns the updated document :该操作将返回更新后的文档: