On this page本页内容
db.collection.
updateOne
(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 within the collection based on the filter.根据筛选器更新集合中的单个文档。
The updateOne()
method has the following syntax:语法如下所示:
The db.collection.updateOne()
method takes the following parameters:db.collection.updateOne()
方法采用以下参数:
filter | document |
| ||||
update | document or pipeline |
| ||||
upsert |
boolean |
| ||||
writeConcern |
document |
| ||||
collation |
document |
| ||||
arrayFilters |
array |
Note
| ||||
hint | Document or string |
|
The method returns a document that contains:该方法返回一个包含以下内容的文档:
matchedCount
modifiedCount
upsertedId
_id
for the upserted document._id
。acknowledged
as true
if the operation ran with write concern or false
if write concern was disabledacknowledged
为true
;如果写关注点被禁用,则布尔值acknowledged
为false
On deployments running with 在使用授权运行的部署中,用户必须具有包括以下权限的访问权限:authorization
, the user must have access that includes the following privileges:
update
action on the specified collection(s).update
操作。find
action on the specified collection(s).find
操作。insert
action on the specified collection(s) if the operation results in an upsert.insert
操作。The built-in role 内置角色readWrite
provides the required privileges.readWrite
提供所需的权限。
db.collection.updateOne()
finds the first document that matches the filter and applies the specified update modifications.查找与筛选器匹配的第一个文档,并应用指定的更新修改。
For the update specifications, the 对于更新规范,db.collection.updateOne()
method can accept a document that only contains update operator expressions.db.collection.updateOne()
方法可以接受只包含更新运算符表达式的文档。
For example:例如:
Starting in MongoDB 4.2, the 从MongoDB 4.2开始,db.collection.updateOne()
method can accept an aggregation pipeline [ <stage1>, <stage2>, ... ]
that specifies the modifications to perform. db.collection.updateOne()
方法可以接受聚合管道[ <stage1>, <stage2>, ... ]
指定要执行的修改。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:例如:
Note
The 管道中使用的$set
and $unset
used in the pipeline refers to the aggregation stages $set
and $unset
respectively, and not the update operators $set
and $unset
.$set
和$unset
分别指的是聚合阶段 $set
和$unset
,而不是更新运算符$set
和$unset
。
For examples, see Update with Aggregation Pipeline.有关示例,请参阅使用聚合管道更新。
If 如果upsert: true
and no documents match the filter
, db.collection.updateOne()
creates a new document based on the filter
criteria and update
modifications. upsert:true
且没有与filter
匹配的文档,db.collection.updateOne()
将根据filter
条件和update
修改创建一个新文档。See Update with Upsert.请参阅使用Upsert更新。
If you specify 如果在分片集合上指定upsert: true
on a sharded collection, you must include the full shard key in the filter. upsert:true
,则必须在筛选器中包含完整的分片密钥。For additional 有关分片集合的其他db.collection.updateOne()
behavior on a sharded collection, see Sharded Collections.db.collection.updateOne()
行为,请参阅分片集合。
If an update operation changes the document size, the operation will fail.如果更新操作更改了文档大小,则操作将失败。
upsert
on a Sharded Collectionupsert
¶To use 要在分片集合上使用db.collection.updateOne()
on a sharded collection:db.collection.updateOne()
:
upsert: true
, you must include an exact match on the _id
field or target a single shard (such as by including the shard key in the filter).upsert:true
,则必须在_id
字段中包含精确匹配项,或将单个碎片作为目标(例如,通过在筛选器中包含碎片键)。upsert: true
, the filter must include the shard key.upsert:true
,则筛选器必须包含碎片密钥。However, 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开始,可以更新文档的shard key值,除非分片键字段是不可变的_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。Take precaution to avoid accidentally removing the shard key when changing a document’s shard key value.采取预防措施,以避免在更改文档的shard key值时意外删除shard key。
To modify the existing shard key value with 要使用db.collection.updateOne()
:db.collection.updateOne()
修改现有切分键值,请执行以下操作:
mongos
. mongos
上运行。See also upsert on a Sharded Collection.另请参见在分片集合上upsert。
Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 从4.4版开始,切分集合中的文档可能会缺少切分键字段。To use 要使用db.collection.updateOne()
to set the document’s missing shard key, you must run on a mongos
. db.collection.updateOne()
设置文档缺少的碎片密钥,必须在mongos
上运行。Do not issue the operation directly on the shard.不要直接在分片上发布操作。
In addition, the following requirements also apply:此外,以下要求也适用:
null null |
|
null valuenull 值 |
|
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:另见:
updateOne()
is not compatible with 与db.collection.explain()
.不兼容。
db.collection.updateOne()
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.updateOne()
with upsert: true
can be run against an existing collection or a non-existing collection. "4.4"
或更高版本的,可以对现有集合或不存在的集合运行带有upsert:true
的db.collection.updateOne()
。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.要将写关注点用于事务,请参阅事务和写关注点。
The restaurant
collection contains the following documents:restaurant
集合包含以下文档:
The following operation updates a single document where 以下操作将更新一个name: "Central Perk Cafe"
with the violations
field:name
为"Central Perk Cafe"
的文档,其中包含violations
字段:
The operation returns:操作返回:
If no matches were found, the operation instead returns:如果未找到匹配项,则操作将返回:
Setting 如果未找到匹配项,则设置upsert: true
would insert the document if no match was found. upsert:true
将插入文档。See Update with Upsert请参阅使用Upsert更新
Starting in MongoDB 4.2, the 从MongoDB 4.2开始,db.collection.updateOne()
can use an aggregation pipeline for the update. db.collection.updateOne()
可以使用聚合管道进行更新。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语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。
The following examples uses the aggregation pipeline to modify a field using the values of the other fields in the document.以下示例使用聚合管道使用文档中其他字段的值修改字段。
Create a 使用以下文档创建members
collection with the following documents:members
集合:
Assume that instead of separate 假设您不想在第一个文档中单独显示misc1
and misc2
fields in the first document, you want to gather these into a comments
field, like the second document. misc1
和misc2
字段,而是希望将它们收集到一个comments
字段中,就像第二个文档一样。The following update operation uses an aggregation pipeline to:以下更新操作使用聚合管道来:
comments
field and set the lastUpdate
field.comments
字段并设置lastUpdate
字段。misc1
and misc2
fields for all documents in the collection.misc1
和misc2
字段。Note
The 管道中使用的$set
and $unset
used in the pipeline refers to the aggregation stages $set
and $unset
respectively, and not the update operators $set
and $unset
.$set
和$unset
分别指的是聚合阶段$set
和$unset
,而不是更新运算符$set
和$unset
。
comments
whose elements are the current content of the misc1
and misc2
fields andcomments
,其元素是misc1
和misc2
字段的当前内容,以及lastUpdate
to the value of the aggregation variable NOW
. lastUpdate
设置为聚合变量NOW
的值。NOW
resolves to the current datetime value and remains the same throughout the pipeline. NOW
解析为当前日期时间值,并在整个管道中保持不变。$$
and enclose in quotes.$$
并用引号括起来。$unset
stage removes the misc1
and misc2
fields.$unset
阶段删除misc1
和misc2
字段。After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
The aggregation pipeline allows the update to perform conditional updates based on the current field values as well as use current field values to calculate a separate field value.聚合管道允许更新基于当前字段值执行条件更新,并使用当前字段值计算单独的字段值。
For example, create a 例如,使用以下文档创建students3
collection with the following documents:students3
集合:
The third document 第三个文档_id: 3
is missing the average
and grade
fields. _id:3
缺少average
和grade
字段。Using an aggregation pipeline, you can update the document with the calculated grade average and letter grade.使用聚合管道,可以使用计算出的平均成绩和字母成绩更新文档。
Note
The 管道中使用的$set
used in the pipeline refers to the aggregation stage $set
, and not the update operators $set
.$set
指的是聚合阶段$set
,而不是更新运算符$set
。
average
based on the average of the tests
field. test
字段的平均值计算新字段average
。$avg
for more information on the $avg
aggregation operator and $trunc
for more information on the $trunc
truncate aggregation operator.$avg
聚合运算符的更多信息,请参阅$avg
;有关$trunc
截断聚合运算符的更多信息,请参见$trunc
。lastUpdate
to the value of the aggregation variable NOW
. lastUpdate
设置为聚合变量NOW
的值。NOW
resolves to the current datetime value and remains the same throughout the pipeline. NOW
解析为当前日期时间值,并在整个管道中保持不变。$$
and enclose in quotes.$$
并用引号括起来。$set
stage calculates a new field grade
based on the average
field calculated in the previous stage. $set
阶段根据前一阶段计算的平均字段计算新的字段等级。$switch
for more information on the $switch
aggregation operator.$switch
聚合运算符的更多信息,请参阅$switch
。After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
See also参阅
The restaurant
collection contains the following documents:restaurant
集合包含以下文档:
The following operation attempts to update the document with 以下操作将尝试更新name : "Pizza Rat's Pizzaria"
, while upsert: true
:name
为"Pizza Rat's Pizzaria"
的文档,而upsert:true
:
Since 自upsert:true
the document is inserted
based on the filter
and update
criteria. upsert:true
起,根据filter
和update
条件插入文档。The operation returns:操作返回:
The collection now contains the following documents:该集合现在包含以下文档:
The name
field was filled in using the filter
criteria, while the update
operators were used to create the rest of the document.name
字段使用filter
条件填充,而update
运算符用于创建文档的其余部分。
The following operation updates the first document with 以下操作将使用大于violations
that are greater than 10
:10
的violations
更新第一个文档:
The operation returns:操作返回:
The collection now contains the following documents:该集合现在包含以下文档:
Since no documents matched the filter, and 由于没有与筛选器匹配的文档,且upsert
was true
, updateOne
inserted the document with a generated _id
and the update
criteria only.upsert
为true
,因此updateOne
仅使用生成的_id
和update
条件插入文档。
Given a three member replica set, the following operation specifies a 给定一个由三个成员组成的副本集,以下操作指定w
of majority
, wtimeout
of 100
:w:majority
,wtimeout:100
:
If the primary and at least one secondary acknowledge each write operation within 100 milliseconds, it returns:如果主设备和至少一个辅助设备在100毫秒内确认每个写入操作,则返回:
If the acknowledgement takes longer than the 如果确认时间超过wtimeout
limit, the following exception is thrown:wtimeout
限制,则会引发以下异常:
Changed in version 4.4.在版本4.4中更改。
The following table explains the possible values of 下表说明了errInfo.writeConcern.provenance
:errInfo.writeConcern.provenance
的可能值:
clientSupplied |
|
customDefault |
setDefaultRWConcern .setDefaultRWConcern 。 |
getLastErrorDefaults |
settings.getLastErrorDefaults field.settings.getLastErrorDefaults 字段。 |
implicitDefault |
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:以下操作包括排序规则选项:
arrayFilters
for an Array Update OperationsarrayFilters
¶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
条件¶Create a collection 创建一个包含以下文档的students
with the following documents:students
集合:
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.updateOne
method:grades
数组中大于或等于100
的所有元素,请在db.collection.updateOne
方法中使用筛选的位置运算符$[<identifier>]
和arrayFilters
选项:
The operation updates the 该操作会更新单个文档的grades
field of a single document, and after the operation, the collection has the following documents:grades
字段,操作完成后,集合中有以下文档:
Create a collection 使用以下文档创建students2
with the following documents:students2
集合:
To modify the value of the 要修改等级大于或等于mean
field for all elements in the grades
array where the grade is greater than or equal to 85
, use the filtered positional operator $[<identifier>]
with the arrayFilters
in the db.collection.updateOne
method:85
的grades
数组中所有元素的mean
(平均值)字段,请在db.collection.updateOne
方法中使用筛选的位置运算符$[<identifier>]
和arrayFilters
:
The operation updates the array of a single document, and after the operation, the collection has the following documents:该操作将更新单个文档的数组,操作完成后,集合将包含以下文档:
hint
for Update Operationshint
¶New in version 4.2.1.在4.2.1版中新增。
Create a sample 使用以下文档创建示例members
collection with the following documents:members
集合:
Create the following indexes on the collection:在集合上创建以下索引:
The following update operation explicitly hints to use the index 以下更新操作明确提示使用索引{ status: 1 }
:{ status: 1 }
:
Note
If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作将出错。
The update command returns the following:update命令返回以下内容:
To view the indexes used, you can use the 要查看使用的索引,可以使用$indexStats
pipeline:$indexStats
管道:
See also参阅
To update multiple documents, see 要更新多个文档,请参阅db.collection.updateMany()
.db.collection.updateMany()
。