On this page本页内容
update
¶The update
command modifies documents in a collection. update
命令修改集合中的文档。A single 一个update
command can contain multiple update statements. update
命令可以包含多个更新语句。The update methods provided by the MongoDB drivers use this command internally.MongoDB驱动程序提供的更新方法在内部使用此命令。
The mongo
shell provides the following helper methods:mongo
shell提供以下帮助程序方法:
Changed in version 4.2.在版本4.2中更改。
The update
command has the following syntax:update
命令语法如下所示:
The command takes the following fields:该命令包含以下字段:
update |
string | |
updates |
array | |
ordered |
boolean | true , then when an update statement fails, return without performing the remaining update statements. true ,则当update 语句失败时,返回而不执行其余的update 语句。false , then when an update fails, continue with the remaining update statements, if any. false ,则当更新失败时,继续执行剩余的update 语句(如果有)。true .true 。 |
writeConcern |
document |
|
bypassDocumentValidation |
boolean |
|
comment |
any |
|
Each element of the updates
array is an update statement document. updates
数组的每个元素都是一个update语句文档。Each document contains the following fields:每个文档都包含以下字段:
q | document |
|
u |
| |
upsert | boolean |
|
multi |
boolean | true , updates all documents that meet the query criteria. true ,则更新满足查询条件的所有文档。false , limit the update to one document that meet the query criteria. false ,则将更新限制为满足查询条件的一个文档。false .false 。 |
collation |
document |
The collation option
|
arrayFilters |
array |
Note
|
hint |
|
On deployments running with 在使用authorization
, the user must have access that includes the following privileges:authorization
运行的部署中,用户必须具有包括以下权限的访问权限:
update
action on the specified collection(s).update
操作。find
action on the specified collection(s).find
操作。insert
action on the specified collection(s).insert
操作。The built-in role 内置角色readWrite
provides the required privileges.readWrite
提供所需的权限。
The update statement field u can accept a document that only contains update operator expressions. update
语句字段u可以接受仅包含更新运算符表达式的文档。For example:例如:
Then, the 然后,update
command updates only the corresponding fields in the document.update
命令只更新文档中相应的字段。
The update statement field u field can accept a replacement document, i.e. the document contains only field:value
expressions. update
语句字段u字段可以接受替换文档,即该文档只包含field:value
表达式。For example:例如:
Then the 然后,update
command replaces the matching document with the update document. update
命令将匹配的文档替换为更新文档。The update
command can only replace a single matching document; i.e. the multi
field cannot be true
. update
命令只能替换单个匹配的文档;亦即,多字段不可能是真的。The update
command does not replace the _id
value.update
命令不会替换_id
值。
Starting in MongoDB 4.2, the update statement field u field can accept an aggregation pipeline 从MongoDB 4.2开始,[ <stage1>, <stage2>, ... ]
that specifies the modifications to perform. update
语句字段u
字段可以接受聚合管道[ <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.有关示例,请参阅使用聚合管道更新。
For each update element in the 对于updates
array, the sum of the query and the update sizes (i.e. q
and u
) must be less than or equal to the maximum BSON document size
.updates
数组中的每个更新元素,查询和更新大小(即q
和u
)之和必须小于或等于maximum BSON document size
。
The total number of update statements in the updates
array must be less than or equal to the maximum bulk size
.updates
数组中update
语句的总数必须小于或等于最大批量大小。
The update
command adds support for the bypassDocumentValidation
option, which lets you bypass document validation when inserting or updating documents in a collection with validation rules.update
命令添加了对bypassDocumentValidation
选项的支持,该选项允许在使用验证规则插入或更新集合中的文档时绕过文档验证。
upsert
on a Sharded Collectionupsert
¶To use update
with multi: false
on a sharded collection,
_id
field or target a single shard (such as by including the shard key).However, 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, when replacing a document, 从MongoDB 4.2开始,在替换文档时,update
attempts to target a shard, first by using the query filter. update
会首先使用查询筛选器尝试将碎片作为目标。If the operation cannot target a single shard by the query filter, it then attempts to target by the replacement document.如果操作无法通过查询筛选器以单个碎片为目标,那么它将尝试通过替换文档以该碎片为目标。
In earlier versions, the operation attempts to target using the replacement document.在早期版本中,该操作尝试使用替换文档作为目标。
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之前,文档的shard key字段值是不可变的。
To modify the existing shard key value with 要使用update
:update
修改现有的分片键值,请执行以下操作:
mongos
. Do not
issue the operation directly on the shard.multi: false
.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 upsert on a Sharded Collection.另请参见在分片集合上upsert。
Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. To use update
to set the document’s missing shard key, you must run on a mongos
. Do not issue the operation directly on the shard.
In addition, the following requirements also apply:此外,以下要求也适用:
To set to null |
|
null value: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:
update
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, update
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.要将写关注点用于事务,请参阅事务和写关注点。
Use update operators to update only the specified fields of a document.使用更新运算符仅更新文档的指定字段。
For example, create a 例如,使用以下文档创建members
collection with the following documents:members
集合:
The following command uses the $set
and $inc
update operators to update the status
and the points
fields of a document where the member
equals "abc123"
:
Because 因为<update>
document does not specify the optional multi
field, the update only modifies one document, even if more than one document matches the q
match condition.<update>
文档没有指定可选的multi
字段,所以更新只修改一个文档,即使有多个文档符合q
匹配条件。
The returned document shows that the command found and updated a single document. 返回的文档显示命令找到并更新了一个文档。The command returns:命令返回:
See Output for details.有关详细信息,请参阅输出。
After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
Use update operators to update only the specified fields of a document, and include the multi
field set to true
in the update statement.
For example, a 例如,members
collection contains the following documents:members
集合包含以下文档:
The following command uses the $set
and $inc
update operators to modify the status
and the points
fields respectively of all documents in the collection:
The update modifies all documents that match the query specified in the 更新将修改与q
field, namely the empty query which matches all documents in the collection.q
字段中指定的查询匹配的所有文档,即与集合中的所有文档匹配的空查询。
The returned document shows that the command found and updated multiple documents. 返回的文档显示命令找到并更新了多个文档。 For a replica set, the command returns:对于副本集,该命令返回:
See Output for details.有关详细信息,请参阅输出。
After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
Starting in MongoDB 4.2, the update
command can use an aggregation pipeline for the update. The pipeline can consist of the following stages:
$addFields
and its alias $set
$project
and its alias $unset
$replaceRoot
and its alias $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.以下示例使用聚合管道使用文档中其他字段的值修改字段。
A members
collection contains the following documents:members
集合包含以下文档:
Assume that instead of separate 假设不需要单独的misc1
and misc2
fields, you want to gather these into a new comments
field. misc1
和misc2
字段,而是希望将它们收集到一个新的comments
字段中。The following update operation uses an aggregation pipeline to add the new 以下更新操作使用聚合管道添加新comments
field and remove the misc1
and misc2
fields for all documents in the collection.comments
字段,并删除集合中所有文档的misc1
和misc2
字段。
status
field to "Modified"
and add a new field comments
that contains the current contents of two other fields misc1
and misc2
fields.misc1
and misc2
fields.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
.
The returned document shows that the command found and updated multiple documents. 返回的文档显示命令找到并更新了多个文档。 The command returns:命令返回:
See Output for details.有关详细信息,请参阅输出。
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.聚合管道允许更新基于当前字段值执行条件更新,并使用当前字段值计算单独的字段值。
Using an aggregation pipeline, you can update the documents 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
stage calculates a new field average
based on the average of the tests
field. See $avg
for more information on the $avg
aggregation operator.$set
stage calculates a new field grade
based on the average
field calculated in the previous stage. See $switch
for more information on the $switch
aggregation operator.The returned document shows that the command found and updated multiple documents. 返回的文档显示命令找到并更新了多个文档。The command returns:命令返回:
After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
The following example performs multiple update operations on the 以下示例对members
collection:members
集合执行多个更新操作:
The returned document shows that the command modified 返回的文档显示,该命令修改了10
documents and inserted a document with the _id
value 5
. 10
个文档,并插入了一个_id
值为5
的文档。See Output for details.有关详细信息,请参阅输出。
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 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:
After the operation, the collection contains the following documents:操作完成后,集合包含以下文档:
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
:
After the operation, the collection has the following documents:操作完成后,集合具有以下文档:
hint
for Update Operationshint
¶New in version 4.2.版本4.2中的新功能。
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 see the index used, run 要查看使用的索引,请对操作运行explain
on the operation:explain
:
The returned document contains a subset of the following fields:返回的文档包含以下字段的子集:
update.
ok
¶The status of the command.命令的状态。
update.
n
¶The number of documents selected for update. 选择要更新的文档数。If the update operation results in no change to the document, e.g. 如果更新操作不会导致文档发生任何更改,例如,$set
expression updates the value to the current value, n
can be greater than nModified
.$set
表达式将值更新为当前值,则n
可以大于nModified
。
update.
nModified
¶The number of documents updated. 更新的文档数。If the update operation results in no change to the document, such as setting the value of the field to its current value, 如果更新操作不会导致文档发生任何更改,例如将字段的值设置为其当前值,则nModified
can be less than n
.nModified
可以小于n
。
update.
upserted
¶An array of documents that contains information for each document inserted through the update with 文档数组,其中包含通过upsert: true
.upsert:true
更新插入的每个文档的信息。
Each document contains the following information:每个文档都包含以下信息:
update.upserted.
index
¶An integer that identifies the update with 在updates数组中使用upsert:true
statement in the updates
array, which uses a zero-based index.upsert:true
语句标识更新的整数,updates
数组使用从零开始的索引。
update.upserted.
_id
¶The 添加文档的_id
value of the added document._id
值。
update.
writeErrors
¶An array of documents that contains information regarding any error encountered during the update operation. 包含有关更新操作期间遇到的任何错误的信息的文档数组。The writeErrors
array contains an error document for each update statement that errors.writeErrors
数组包含每个发生错误的update语句的错误文档。
Each error document contains the following fields:每个错误文档都包含以下字段:
update.writeErrors.
index
¶An integer that identifies the update statement in the 一个整数,用于标识updates
array, which uses a zero-based index.updates
数组中的update语句,该数组使用基于零的索引。
update.writeErrors.
code
¶An integer value identifying the error.标识错误的整数值。
update.writeErrors.
errmsg
¶A description of the error.对错误的描述。
update.
writeConcernError
¶Document that describe error related to write concern and contains the field:描述与写入问题相关的错误的文档,包含以下字段:
update.writeConcernError.
code
¶An integer value identifying the cause of the write concern error.标识写入问题错误原因的整数值。
update.writeConcernError.
errmsg
¶A description of the cause of the write concern error.对写入问题错误原因的描述。
update.writeConcernError.errInfo.
writeConcern
¶New in version 4.4.版本4.4中的新功能。
The write concern object used for the corresponding operation. 用于相应操作的写关注点对象。For information on write concern object fields, see Write Concern Specification.有关写入关注点对象字段的信息,请参阅写入关注点规范。
The write concern object may also contain the following field, indicating the source of the write concern:写关注点对象还可能包含以下字段,指示写关注点的来源:
update.writeConcernError.errInfo.writeConcern.
provenance
¶A string value indicating where the write concern originated (known as write concern 一个字符串值,指示写关注点的来源(称为写关注点provenance
). provenance
)。The following table shows the possible values for this field and their significance:下表显示了该字段的可能值及其重要性:
Provenance | |
---|---|
clientSupplied |
|
customDefault |
setDefaultRWConcern . |
getLastErrorDefaults |
settings.getLastErrorDefaults field.settings.getLastErrorDefaults 字段。 |
implicitDefault |
In addition to the aforementioned update specific return fields, the 除了上述特定于更新的返回字段外,db.runCommand()
includes additional information:db.runCommand()
包含其他信息:
optime
, electionId
, $clusterTime
, and operationTime
.optime
、electionId
、$clusterTime
和operationTime
。operationTime
and $clusterTime
.operationTime
和$clusterTime
。See db.runCommand Response for details on these fields.有关这些字段的详细信息,请参阅db.runCommand
响应。
The following is an example document returned for a successful 以下是成功执行upsert的update
command that performed an upsert:update
命令返回的示例文档:
The following is an example document returned for a bulk update involving three update statements, where one update statement was successful and two other update statements encountered errors:以下是批量更新返回的示例文档,涉及三条update语句,其中一条update语句成功,另两条update语句遇到错误: