Docs HomeMongoDB Manual

update

Definition定义

update

The update command modifies documents in a collection. update命令用于修改集合中的文档。A single update command can contain multiple update statements.单个update命令可以包含多个更新语句。

Tip

In mongosh, this command can also be run through the updateOne(), updateMany(), replaceOne(), findOneAndReplace(), and findOneAndUpdate() helper methods.mongosh中,此命令也可以通过updateOne(), updateMany()replaceOne()findOneAndReplace()findOneAndUpdate()辅助方法运行。

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. 助手方法对mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。In cases where the convenience is not needed or the additional return fields are required, use the database command.如果不需要方便,或者需要额外的返回字段,请使用数据库命令。

Syntax语法

Changed in version 5.0.5.0版更改。

The command has the following syntax:该命令具有以下语法:

db.runCommand(
{
update: <collection>,
updates: [
{
q: <query>,
u: <document or pipeline>,
c: <document>, // Added in MongoDB 5.0
upsert: <boolean>,
multi: <boolean>,
collation: <document>,
arrayFilters: <array>,
hint: <document|string>
},
...
],
ordered: <boolean>,
maxTimeMS: <integer>,
writeConcern: { <write concern> },
bypassDocumentValidation: <boolean>,
comment: <any>,
let: <document> // Added in MongoDB 5.0
}
)

Command Fields命令字段

The command takes the following fields:该命令包含以下字段:

Field字段Type类型Description描述
updatestringThe name of the target collection.目标集合的名称。
updatesarrayAn array of one or more update statements to perform on the named collection. 要对命名集合执行的一个或多个更新语句的数组。For details of the update statements, see Update Statements.有关更新语句的详细信息,请参阅更新语句。
orderedbooleanOptional.可选的。If true, then when an update statement fails, return without performing the remaining update statements. 如果为true,则当更新语句失败时,返回而不执行其余的更新语句。If false, then when an update fails, continue with the remaining update statements, if any. 如果为false,则当更新失败时,继续使用剩余的更新语句(如果有的话)。Defaults to true.默认为true
maxTimeMSnon-negative integerOptional.可选的。
Specifies a time limit in milliseconds. 指定以毫秒为单位的时间限制。If you do not specify a value for maxTimeMS, operations will not time out. 如果不指定maxTimeMS的值,操作将不会超时。A value of 0 explicitly specifies the default unbounded behavior.0显式指定默认的无边界行为。
MongoDB terminates operations that exceed their allotted time limit using the same mechanism as db.killOp(). MongoDB使用与db.killOp()相同的机制终止超过指定时间限制的操作。MongoDB only terminates an operation at one of its designated interrupt points. MongoDB只在其指定的中断点之一终止操作。
writeConcerndocumentOptional.可选的。A document expressing the write concern of the update command. 表示update命令的写入关注的文档。Omit to use the default write concern.忽略使用默认的写入关注。
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. 要在事务中使用写入关注,请参阅事务和写入关注
bypassDocumentValidationbooleanOptional.可选的。Enables update to bypass document validation during the operation. 启用update以在操作期间绕过文档验证。This lets you update documents that do not meet the validation requirements.这样可以更新不符合验证要求的文档。
commentanyOptional.可选的。
A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations: 要附加到此命令的用户提供的注释。设置后,此注释将与此命令的记录一起显示在以下位置: A comment can be any valid BSON type (string, integer, object, array, etc). 注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。
New in version 4.4. 4.4版新增。
letdocumentOptional.可选的。
Specifies a document with a list of variables. This allows you to improve command readability by separating the variables from the query text.指定具有变量列表的文档。这允许您通过将变量与查询文本分离来提高命令的可读性。
The document syntax is: 文档语法为:
{ <variable_name_1>: <expression_1>,
...,
<variable_name_n>: <expression_n> }
The variable is set to the value returned by the expression, and cannot be changed afterwards.变量设置为表达式返回的值,之后不能更改。
To access the value of a variable in the command, use the double dollar sign prefix ($$) together with your variable name in the form $$<variable_name>. 要访问命令中变量的值,请使用双美元符号前缀($$)和形式为$$<variable_name>的变量名。For example: $$targetTotal.例如:$$targetTotal
For a complete example, see Use Variables in let Option or c Field.有关完整的示例,请参阅let选项或c字段中使用变量
New in version 5.0. 5.0版新增。

Update Statements更新报表

Each element of the updates array is an update statement document. Each document contains the following fields:updates数组的每个元素都是一个update语句文档。每个文档都包含以下字段:

Field字段Type类型Description描述
qdocumentThe query that matches documents to update. 与要更新的文档匹配的查询。Use the same query selectors as used in the find() method. 使用与find()方法中使用的查询选择器相同的查询选择器
udocument or pipelineThe modifications to apply. The value can be either: 要应用的修改。该值可以是: For details, see Behavior. 有关详细信息,请参阅行为
cdocumentOptional.可选的。
Specifies a document with a list of variables. This allows you to improve command readability by separating the variables from the query text.指定具有变量列表的文档。这允许您通过将变量与查询文本分离来提高命令的可读性。
The document syntax is: 文档语法为:
{ <variable_name_1>: <expression_1>,
...,
<variable_name_n>: <expression_n> }
The variable is set to the value returned by the expression, and cannot be changed afterwards.变量设置为表达式返回的值,之后不能更改。
To access the value of a variable in the command, use the double dollar sign prefix ($$) together with your variable name in the form $$<variable_name>. 要访问命令中变量的值,请使用双美元符号前缀($$)和形式为$$<variable_name>的变量名。For example: $$targetTotal. 例如:$$targetTotal
Note
To use a variable to filter results, you must access the variable within the $expr operator. 若要使用变量筛选结果,必须访问$expr运算符中的变量。
For a complete example using let and variables, see Use Variables in let Option or c Field. 有关使用let和变量的完整示例,请参阅let选项或c字段中使用变量
New in version 5.0. 5.0版新增。
upsertbooleanOptional.可选的。When true, update either: 如果为true,请update其中一个:
  • Creates a new document if no documents match the query. 如果没有与query匹配的文档,则创建新文档。For more details see upsert behavior.有关更多详细信息,请参阅upsert行为
  • Updates a single document that matches the query.更新与query匹配的单个文档。
If both upsert and multi are true and no documents match the query, the update operation inserts only a single document.如果upsertmulti都为true,并且没有与查询匹配的文档,则更新操作仅插入单个文档。
To avoid multiple upserts, ensure that the query field(s) are uniquely indexed. 为了避免多个upsert,请确保query字段的索引是唯一的See Upsert with Unique Index for an example.有关示例,请参阅具有唯一索引的Upsert
Defaults to false, which does not insert a new document when no match is found. 默认为false,在找不到匹配项时不插入新文档。
multibooleanOptional.可选的。If true, updates all documents that meet the query criteria. 如果为true,则更新符合查询条件的所有文档。If false, limit the update to one document that meet the query criteria. 如果为false,则将更新限制为一个符合查询条件的文档。Defaults to false.默认为false
When updating multiple documents, if a single document fails to update, further documents are not updated. 更新多个文档时,如果单个文档无法更新,则不会更新其他文档。See multi-update failures for more details on this behavior. 有关此行为的更多详细信息,请参阅multi更新失败
collationdocumentOptional.可选的。
Specifies the collation to use for the operation.指定要用于操作的排序规则
collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音标记的规则。
The collation option has the following syntax: collation选项具有以下语法:
collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
When specifying collation, the locale field is mandatory; all other collation fields are optional. 指定排序规则时,locale字段是必需的;所有其他排序规则字段都是可选的。For descriptions of the fields, see Collation Document.有关字段的说明,请参阅排序规则文档
If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.如果未指定排序规则,但集合具有默认排序规则(请参见db.createCollection()),则操作将使用为集合指定的排序规则。
If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.如果没有为集合或操作指定排序规则,MongoDB将使用以前版本中使用的简单二进制比较进行字符串比较。
You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort. 不能为一个操作指定多个排序规则。例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能为查找使用一个排序规则,为排序使用另一个排序顺序。
arrayFiltersarrayOptional.可选的。An array of filter documents that determines which array elements to modify for an update operation on an array field.筛选文档的数组,用于确定要为数组字段的更新操作修改哪些数组元素。
In the update document, use the $[<identifier>] filtered positional operator to define an identifier, which you then reference in the array filter documents. 在更新文档中,使用$[<identifier>]筛选的位置运算符来定义标识符,然后在数组筛选文档中引用该标识符。You cannot have an array filter document for an identifier if the identifier is not included in the update document. 如果标识符未包含在更新文档中,则不能为该标识符设置数组筛选器文档。
Note
The <identifier> must begin with a lowercase letter and contain only alphanumeric characters. <identifier>必须以小写字母开头,并且仅包含字母数字字符。
You can include the same identifier multiple times in the update document; however, for each distinct identifier ($[identifier]) in the update document, you must specify exactly one corresponding array filter document. 您可以在更新文档中多次包含相同的标识符;但是,对于更新文档中的每个不同标识符($[identifier]),必须指定恰好一个对应的数组筛选器文档。That is, you cannot specify multiple array filter documents for the same identifier. 也就是说,不能为同一标识符指定多个数组筛选器文档。For example, if the update statement includes the identifier x (possibly multiple times), you cannot specify the following for arrayFilters that includes 2 separate filter documents for x: 例如,如果update语句包含标识符x(可能多次),则不能为arrayFilters指定以下内容,因为arrayFilters包含两个单独的x筛选文档:
// INVALID

[
{ "x.a": { $gt: 85 } },
{ "x.b": { $gt: 80 } }
]
However, you can specify compound conditions on the same identifier in a single filter document, such as in the following examples: 但是,您可以在单个筛选器文档中对同一标识符指定复合条件,例如以下示例:
// Example 1
[
{ $or: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }
]
// Example 2
[
{ $and: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }
]
// Example 3
[
{ "x.a": { $gt: 85 }, "x.b": { $gt: 80 } }
]
For examples, see Specify arrayFilters for Array Update Operations. 有关示例,请参阅为数组更新操作指定arrayFilters
hintDocument or stringOptional.可选的。A document or string that specifies the index to use to support the query predicate.指定用于支持查询谓词索引的文档或字符串。
The option can take an index specification document or the index name string.该选项可以采用索引规范文档或索引名称字符串。
If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作将出错。
For an example, see Specify hint for Update Operations. 有关示例,请参阅为更新操作指定hint
New in version 4.2. 4.2版新增。

Returns返回值

The command returns a document that contains the status of the operation. 该命令返回一个包含操作状态的文档。For example:例如:

{
"ok" : 1,
"nModified" : 0,
"n" : 1,
"upserted" : [
{
"index" : 0,
"_id" : ObjectId("52ccb2118908ccd753d65882")
}
]
}

For details of the output fields, see Output.有关输出字段的详细信息,请参阅输出

Access Control访问控制

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提供所需的权限。

Behavior行为

Update with an Update Operator Expressions Document使用更新运算符表达式文档进行更新

The update statement field u can accept a document that only contains update operator expressions. 更新语句字段u可以接受只包含更新运算符表达式的文档。For example:例如:

updates: [
{
q: <query>,
u: { $set: { status: "D" }, $inc: { quantity: 2 } },
...
},
...
]

Then, the update command updates only the corresponding fields in the document.然后,update命令只更新文档中的相应字段。

Update with a Replacement Document使用替换文档更新

The update statement field u field can accept a replacement document, i.e. the document contains only field:value expressions. 更新语句字段u字段可以接受替换文档,即文档包含field:value表达式。For example:例如:

updates: [
{
q: <query>,
u: { status: "D", quantity: 4 },
...
},
...
]

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命令只能替换单个匹配的文档;即multi字段不可能为trueThe update command does not replace the _id value.update命令不会替换_id值。

Multi-Update Failures多次更新失败

If a single document fails to update in an update command with the multi parameter set to true, no further documents update as part of that command.如果在multi参数设置为true的更新命令中单个文档无法更新,则不会有其他文档作为该命令的一部分进行更新。

For example, create a members collection with the following documents:例如,使用以下文档创建members集合:

db.members.insertMany( [
{ "_id" : 1, "member" : "Taylor", "status" : "pending", "points" : 1},
{ "_id" : 2, "member" : "Alexis", "status" : "enrolled", "points" : 59},
{ "_id" : 3, "member" : "Elizabeth", "status" : "enrolled", "points" : 34}
] )

The following operation creates a document validator on the members collection with a rule that the points value can not equal 60.以下操作在members集合上创建一个文档验证器,其规则是points值不能等于60

db.runCommand( {
collMod: "members",
validator: { points: { $ne: 60 } }
} )

This update command increases the points field of every document by 1.此更新命令将每个文档的points字段增加1

db.runCommand(
{
update: "members",
updates: [
{
q: {},
u: { $inc: { points: 1 } },
multi: true
}
]
}
)

After running the command, the collection contains the following documents:运行命令后,集合包含以下文档:

{ _id: 1, member: 'Taylor', status: 'A', points: 2 }
{ _id: 2, member: 'Alexis', status: 'D', points: 59 }
{ _id: 3, member: 'Elizabeth', status: 'C', points: 34 }

The update command updated the points value of the first document but failed to update the second document because of the validator rule that the points value can not equal 60. 更新命令更新了第一个文档的points值,但由于验证器规则points值不能等于60而未能更新第二个文档。The third document did not update because no further documents update following a write error.第三个文档没有更新,因为在写入错误后没有其他文档更新。

Tip

See also: 另请参阅:

Schema Validation架构验证

Update with an Aggregation Pipeline使用聚合管道更新

Starting in MongoDB 4.2, the update statement field u field can accept an aggregation pipeline [ <stage1>, <stage2>, ... ] that specifies the modifications to perform. 从MongoDB 4.2开始,更新语句字段u字段可以接受一个指定要执行的修改的聚合管道[ <stage1>, <stage2>, ... ]The pipeline can consist of the following stages:管道可由以下阶段组成:

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).使用聚合管道可以实现更具表达力的更新语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。

For example:例如:

updates: [
{
q: <query>,
u: [
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
{ $unset: [ "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

For examples, see Update with Aggregation Pipeline.有关示例,请参阅使用聚合管道进行更新

Upsert with Unique Index使用唯一索引upsert

When using the upsert: true option with the update command, and not using a unique index on the query field(s), multiple instances of an update operation with similar query field(s) could result in duplicate documents being inserted in certain circumstances.update命令中使用upsert:true选项,而不对查询字段使用唯一索引时,在某些情况下,具有相似查询字段的update操作的多个实例可能会导致插入重复的文档。

Consider an example where no document with the name Andy exists and multiple clients issue the following command at roughly the same time:考虑一个示例,其中不存在名为Andy的文档,并且多个客户端大致同时发出以下命令:

db.runCommand(
{
update: "people",
updates: [
{ q: { name: "Andy" }, u: { $inc: { score: 1 } }, multi: true, upsert: true }
]
}
)

If all update operations finish the query phase before any client successfully inserts data, and there is no unique index on the name field, each update operation may result in an insert, creating multiple documents with name: Andy.如果所有update操作都在任何客户端成功插入数据之前完成了查询阶段,并且name字段上没有唯一索引,则每次update操作都可能导致插入,从而创建多个name: Andy的文档。

To ensure that only one such document is created, and the other update operations update this new document instead, create a unique index on the name field. This guarantees that only one document with name: Andy is permitted in the collection.要确保只创建一个这样的文档,而其他update操作会更新此新文档,请在name字段上创建一个唯一索引。这保证了集合中只允许一个name: Andy的文档。

With this unique index in place, the multiple update operations now exhibit the following behavior:有了这个唯一的索引,多个update操作现在表现出以下行为:

  • Exactly one update operation will successfully insert a new document.只有一次update操作才能成功插入新文档。
  • All other update operations will update the newly-inserted document, incrementing the score value.所有其他update操作都将更新新插入的文档,从而增加score值。

Limits限制

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数组中的每个update元素,查询和更新大小(即qu)之和必须小于或等于最大BSON文档大小

The total number of update statements in the updates array must be less than or equal to the maximum bulk size.updates数组中的更新语句总数必须小于或等于最大批量大小

Document Validation文件验证

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选项的支持,该选项允许您在使用验证规则插入或更新集合中的文档时绕过文档验证

Sharded Collections分片集合

upsert on a Sharded Collection分片集合上的upsert

To use update with multi: false on a sharded collection,要在分片集合上使用update配合multi: false

  • If you do not specify upsert: true, the filter q must either include an equality match on the _id field or target a single shard (such as by including the shard key).如果没有指定upsert: true,那么筛选器q必须在_id字段上包含相等匹配,或者以单个分片为目标(例如通过包含分片键)。
  • If you specify upsert: true, the filter q must include an equality match on the shard key.如果指定upsert: true,那么筛选器q必须在分片键上包含相等匹配。

    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:例如:

    { _id: <value>, <shardkeyfield>: null } // _id of the document missing shard key缺少分片键的文档的_id

Replace Document替换文档

Starting in MongoDB 4.2, when replacing a document, update attempts to target a shard, first by using the query filter. 从MongoDB 4.2开始,在替换文档时,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.在早期版本中,操作尝试使用替换文档作为目标。

Shard Key Modification分片键修改

Starting in MongoDB 4.2, you can update a document's shard key value unless the shard key field is the immutable _id field. 从MongoDB 4.2开始,您可以更新文档的分片键值,除非分片键字段是不可变的_id字段。In MongoDB 4.2 and earlier, a document's shard key field value is immutable.在MongoDB 4.2及更早版本中,文档的分片键字段值是不可变的。

To modify the existing shard key value with update:要使用update修改现有的分片键值,请执行以下操作:

  • You must run on a mongos. 必须mongos上运行。Do not issue the operation directly on the shard.不要直接在分片上发出操作。
  • You must run either in a transaction or as a retryable write.必须事务中运行或作为可重试写入运行。
  • You must specify multi: false.必须指定multi:false
  • You must include an equality query filter on the full shard key.必须在完整的分片键上包含一个相等查询筛选器
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.由于丢失的键值是作为null相等匹配的一部分返回的,为了避免更新null值的键,请酌情包括额外的查询条件(例如在_id字段上)。

See also upsert on a Sharded Collection.另请参阅分片集合的upsert

Missing Shard Key缺少分片键

Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 从4.4版本开始,分片集合中的文档可能会缺少分片键字段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.要使用update设置文档缺少的分片键,必须在mongos上运行。不要直接在分片上发出操作。

In addition, the following requirements also apply:此外,以下要求也适用:

Task任务Requirements要求
To set to null设置为null
  • Can specify multi: true.可以指定multi:true
  • Requires equality filter on the full shard key if upsert: true is specified.如果指定了upsert:true,则需要对完整的分片键进行相等筛选器。
To set to a non-null value:要设置为非null值:
  • Must be performed either inside a transaction or as a retryable write.必须事务内部或作为可重试写入执行。
  • Must specify multi: false.必须指定multi:false
  • Requires equality filter on the full shard key if either: 如果出现以下情况之一,则需要对完整分片键进行相等筛选器:
    • upsert: true, or
    • if using a replacement document and the new shard key value belongs to a different shard.如果使用替换文档,并且新的分片键值属于不同的分片。
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.由于丢失的键值是作为null相等匹配的一部分返回的,为了避免更新null值的键,请酌情包括额外的查询条件(例如在_id字段上)。

See also:另请参阅:

Transactions事务

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.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项

Upsert within Transactions事务中的Upsert

Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.从MongoDB 4.4开始,如果多文档事务不是跨分片写入事务,则可以在该事务内创建集合和索引。

Specifically, in MongoDB 4.4 and greater, update with upsert: true can be run on an existing collection or a non-existing collection. 具体来说,在MongoDB 4.4及更高版本中,可以在现有集合或不存在的集合上运行update配合upsert:trueIf run on a non-existing collection, the operation creates the collection.如果在不存在的集合上运行,则该操作将创建该集合。

In MongoDB 4.2 and earlier, the operation must be run on an existing collection.在MongoDB 4.2及更早版本中,操作必须在现有集合上运行。

Write Concerns and Transactions撰写关注事项和事务

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.如果在事务中运行,请不要显式设置操作的写入关注。要在事务中使用写入关注,请参阅事务和写入关注

Examples实例

Update Specific Fields of One Document更新一个文档的特定字段

Use update operators to update only the specified fields of a document.使用更新运算符仅更新文档的指定字段。

For example, create a members collection with the following documents:例如,使用以下文档创建members集合:

db.members.insertMany([
{ _id: 1, member: "abc123", status: "Pending", points: 0, misc1: "note to self: confirm status", misc2: "Need to activate" },
{ _id: 2, member: "xyz123", status: "D", points: 59, misc1: "reminder: ping me at 100pts", misc2: "Some random comment" },
])

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":以下命令使用$set$inc更新运算符来更新文档的statuspoints字段,其中member等于"abc123"

db.runCommand(
{
update: "members",
updates: [
{
q: { member: "abc123" }, u: { $set: { status: "A" }, $inc: { points: 1 } }
}
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

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:返回的文档显示命令找到并更新了一个文档。命令返回:

{ "n" : 1, "nModified" : 1, "ok" : 1, <additional fields if run on a replica set/sharded cluster> }

See Output for details.有关详细信息,请参阅输出

After the command, the collection contains the following documents:命令之后,集合包含以下文档:

{ "_id" : 1, "member" : "abc123", "status" : "A", "points" : 1, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
{ "_id" : 2, "member" : "xyz123", "status" : "D", "points" : 59, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }

Update Specific Fields of Multiple 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.使用update运算符仅更新文档的指定字段,并在update语句中包含设置为truemulti字段。

For example, a members collection contains the following documents:例如,members集合包含以下文档:

{ "_id" : 1, "member" : "abc123", "status" : "A", "points" : 1, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
{ "_id" : 2, "member" : "xyz123", "status" : "D", "points" : 59, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }

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:以下命令使用$set$inc更新运算符分别修改集合中所有文档的status字段和points字段:

db.runCommand(
{
update: "members",
updates: [
{ q: { }, u: { $set: { status: "A" }, $inc: { points: 1 } }, multi: true }
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

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:返回的文档显示命令找到并更新了多个文档。对于复制副本集,该命令返回:

{ "n" : 2, "nModified" : 2, "ok" : 1,  <additional fields if run on a replica set/sharded cluster> }

See Output for details.有关详细信息,请参阅输出

After the command, the collection contains the following documents:命令之后,集合包含以下文档:

{ "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }

Update with Aggregation Pipeline使用聚合管道更新

Starting in MongoDB 4.2, the update command can use an aggregation pipeline for the update. The pipeline can consist of the following stages:从MongoDB 4.2开始,update命令可以使用聚合管道进行更新。管道可由以下阶段组成:

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).使用聚合管道可以实现更具表达力的更新语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。

Example 1示例1

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集合包含以下文档:

{ "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }

Assume that instead of separate misc1 and misc2 fields, you want to gather these into a new comments field. 假设您不希望将misc1misc2字段分开,而是希望将它们聚集到一个新的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字段并删除misc1misc2字段。

  • First, set the status field to "Modified" and add a new field comments that contains the current contents of two other fields misc1 and misc2 fields.首先,将status字段设置为"Modified",并添加一个新的字段comments,其中包含其他两个字段misc1misc2字段的当前内容。
  • Second, remove the misc1 and misc2 fields.其次,删除misc1misc2字段。
db.runCommand(
{
update: "members",
updates: [
{
q: { },
u: [
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
{ $unset: [ "misc1", "misc2" ] }
],
multi: true
}
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)
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

The returned document shows that the command found and updated multiple documents. The command returns:返回的文档显示命令找到并更新了多个文档。命令返回:

{ "n" : 2, "nModified" : 2, "ok" : 1, <additional fields if run on a replica set/sharded cluster> }

See Output for details.有关详细信息,请参阅输出

After the command, the collection contains the following documents:命令之后,集合包含以下文档:

{ "_id" : 1, "member" : "abc123", "status" : "Modified", "points" : 2, "comments" : [ "note to self: confirm status", "Need to activate" ] }
{ "_id" : 2, "member" : "xyz123", "status" : "Modified", "points" : 60, "comments" : [ "reminder: ping me at 100pts", "Some random comment" ] }

Example 2示例2

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.聚合管道允许更新基于当前字段值执行条件更新,并使用当前字段值计算单独的字段值。

db.students.insertMany( [
{ "_id" : 1, "tests" : [ 95, 92, 90 ] },
{ "_id" : 2, "tests" : [ 94, 88, 90 ] },
{ "_id" : 3, "tests" : [ 70, 75, 82 ] }
] );

Using an aggregation pipeline, you can update the documents with the calculated grade average and letter grade.使用聚合管道,可以使用计算出的平均成绩和字母成绩更新文档。

db.runCommand(
{
update: "students",
updates: [
{
q: { },
u: [
{ $set: { average : { $avg: "$tests" } } },
{ $set: { grade: { $switch: {
branches: [
{ case: { $gte: [ "$average", 90 ] }, then: "A" },
{ case: { $gte: [ "$average", 80 ] }, then: "B" },
{ case: { $gte: [ "$average", 70 ] }, then: "C" },
{ case: { $gte: [ "$average", 60 ] }, then: "D" }
],
default: "F"
} } } }
],
multi: true
}
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)
Note

The $set used in the pipeline refers to the aggregation stage $set, and not the update operators $set.管道中使用的$set指的是聚合阶段$set,而不是更新运算符$set

First Stage第一阶段
The $set stage calculates a new field average based on the average of the tests field. $set阶段根据测试字段的平均值计算新的字段averageSee $avg for more information on the $avg aggregation operator.有关$avg聚合运算符的更多信息,请参阅$avg
Second Stage第二阶段
The $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.$set阶段根据上一阶段中计算的average字段来计算新的字段grade。有关$switch聚合运算符的详细信息,请参阅$switch

The returned document shows that the command found and updated multiple documents. The command returns:返回的文档显示命令找到并更新了多个文档。命令返回:

{ "n" : 3, "nModified" : 3, "ok" : 1, <additional fields if run on a replica set/sharded cluster> }

After the command, the collection contains the following documents:命令之后,集合包含以下文档:

{ "_id" : 1, "tests" : [ 95, 92, 90 ], "average" : 92.33333333333333, "grade" : "A" }
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "average" : 90.66666666666667, "grade" : "A" }
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "average" : 75.66666666666667, "grade" : "C" }

Bulk Update批量更新

The following example performs multiple update operations on the members collection:以下示例对members集合执行多个更新操作:

db.runCommand(
{
update: "members",
updates: [
{ q: { status: "P" }, u: { $set: { status: "D" } }, multi: true },
{ q: { _id: 5 }, u: { _id: 5, name: "abc123", status: "A" }, upsert: true }
],
ordered: false,
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

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.有关详细信息,请参阅输出

{
"ok" : 1,
"nModified" : 10,
"n" : 11,
"upserted" : [
{
"index" : 1,
"_id" : 5
}
]
}

Specify Collation指定排序规则

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包含以下文档:

{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }

The following operation includes the collation option:以下操作包括collation选项:

db.runCommand({
update: "myColl",
updates: [
{ q: { category: "cafe", status: "a" }, u: { $set: { status: "Updated" } }, collation: { locale: "fr", strength: 1 } }
]
})

Specify arrayFilters for Array Update Operations为数组更新操作指定arrayFilters

Starting in MongoDB 3.6, when updating an array field, you can specify arrayFilters that determine which array elements to update.从MongoDB 3.6开始,在更新数组字段时,可以指定arrayFilters来确定要更新的数组元素。

Update Elements Match arrayFilters Criteria更新元素匹配arrayFilters条件

Create a collection students with the following documents:使用以下文档创建students集合:

db.students.insertMany( [
{ "_id" : 1, "grades" : [ 95, 92, 90 ] },
{ "_id" : 2, "grades" : [ 98, 100, 102 ] },
{ "_id" : 3, "grades" : [ 95, 110, 100 ] }
] );

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:要修改grades数组中大于或等于100的所有元素,请将已筛选的位置运算符$[<identifier>]arrayFilters选项一起使用:

db.runCommand( {
update: "students",
updates: [
{ q: { grades: { $gte: 100 } }, u: { $set: { "grades.$[element]" : 100 } }, arrayFilters: [ { "element": { $gte: 100 } } ], multi: true}
]
} )

After the operation, the collection contains the following documents:操作后,集合包含以下文档:

{ "_id" : 1, "grades" : [ 95, 92, 90 ] }
{ "_id" : 2, "grades" : [ 98, 100, 100 ] }
{ "_id" : 3, "grades" : [ 95, 100, 100 ] }

Update Specific Elements of an Array of Documents更新文档数组的特定元素

Create a collection students2 with the following documents:使用以下文档创建集合students2

db.students2.insertMany( [
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 90, "std" : 4 },
{ "grade" : 85, "mean" : 85, "std" : 6 }
]
},
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 75, "std" : 6 },
{ "grade" : 87, "mean" : 90, "std" : 3 },
{ "grade" : 85, "mean" : 85, "std" : 4 }
]
}
] )

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:要修改grades数组中grade大于或等于85的所有元素的mean字段值,请将筛选后的位置运算符$[<identifier>]arrayFilters一起使用:

db.runCommand({
update: "students2",
updates: [
{ q: { }, u: { $set: { "grades.$[elem].mean" : 100 } }, arrayFilters: [ { "elem.grade": { $gte: 85 } } ], multi: true }
]
})

After the operation, the collection has the following documents:操作后,集合具有以下文档:

{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 100, "std" : 4 },
{ "grade" : 85, "mean" : 100, "std" : 6 }
]
}
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 100, "std" : 6 },
{ "grade" : 87, "mean" : 100, "std" : 3 },
{ "grade" : 85, "mean" : 100, "std" : 4 }
]
}

Specify hint for Update Operations指定更新操作的hint

New in version 4.2. 4.2版新增。

Create a sample members collection with the following documents:使用以下文档创建示例members集合:

db.members.insertMany([
{ "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" },
{ "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null },
{ "_id" : 5, "member" : "ijk123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
])

Create the following indexes on the collection:在集合上创建以下索引:

db.members.createIndex( { status: 1 } )
db.members.createIndex( { points: 1 } )

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.如果指定的索引不存在,则操作将出错。

db.runCommand({
update: "members",
updates: [
{ q: { "points": { $lte: 20 }, "status": "P" }, u: { $set: { "misc1": "Need to activate" } }, hint: { status: 1 }, multi: true }
]
})

The update command returns the following:update命令返回以下内容:

{ "n" : 3, "nModified" : 3, "ok" : 1 }

To see the index used, run explain on the operation:要查看使用的索引,请对操作运行explain

db.runCommand(
{
explain: {
update: "members",
updates: [
{ q: { "points": { $lte: 20 }, "status": "P" }, u: { $set: { "misc1": "Need to activate" } }, hint: { status: 1 }, multi: true }
]
},
verbosity: "queryPlanner"
}
)

The explain does not modify the documents.explain不会修改文件。

Use Variables in let Option or c Fieldlet选项或c字段中使用变量

New in version 5.0. 5.0版新增。

Variables can be defined in the let option or the c field and accessed in the updates array.变量可以在let选项或c字段中定义,并在updates数组中访问。

Note

To filter results using a variable, you must access the variable within the $expr operator.若要使用变量筛选结果,必须访问$expr运算符中的变量。

Create a collection cakeFlavors:创建一个集合cakeFlavors

db.cakeFlavors.insertMany( [
{ _id: 1, flavor: "chocolate" },
{ _id: 2, flavor: "strawberry" },
{ _id: 3, flavor: "cherry" }
] )

The following example defines targetFlavor and newFlavor variables in let and uses the variables to change the cake flavor from cherry to orange:以下示例在let中定义targetFlavornewFlavor变量,并使用这些变量将蛋糕口味从樱桃改为橙色:

db.runCommand( {
update: db.cakeFlavors.getName(),
updates: [
{ q: { $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
u: [ { $set: { flavor: "$$newFlavor" } } ] }
],
let : { targetFlavor: "cherry", newFlavor: "orange" }
} )

The next example defines targetFlavor and newFlavor variables in c and uses the variables to change the cake flavor from chocolate to vanilla:下一个示例在c中定义targetFlavornewFlavor变量,并使用这些变量将蛋糕口味从巧克力改为香草:

db.runCommand( {
update: db.cakeFlavors.getName(),
updates: [
{ q: { $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
u: [ { $set: { flavor: "$$newFlavor" } } ],
c: { targetFlavor: "chocolate", newFlavor: "vanilla" } }
]
} )

Output输出

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 upsert:true statement in the updates array, which uses a zero-based index.一个整数,用于在updates数组中使用upsert:true语句标识更新,该数组使用从零开始的索引。

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数组包含每个出错的更新语句的错误文档。

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来源Description描述
clientSuppliedThe write concern was specified in the application.写入关注已在应用程序中指定。
customDefaultThe write concern originated from a custom defined default value. 写入关注源自自定义定义的默认值。See setDefaultRWConcern.
getLastErrorDefaultsThe write concern originated from the replica set's settings.getLastErrorDefaults field.写入关注源自复制副本集的settings.getLastErrorDefaults字段。
implicitDefaultThe write concern originated from the server in absence of all other write concern specifications.在没有所有其他写入关注规范的情况下,写入关注源自服务器。

In addition to the aforementioned update specific return fields, the db.runCommand() includes additional information:除了前面提到的特定于更新的返回字段外,db.runCommand()还包括其他信息:

  • for replica sets: optime, electionId, $clusterTime, and operationTime.对于副本集:optimeelectionId$clusterTimeoperationTime
  • for sharded clusters: 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 update command that performed an upsert:以下是为执行upsert的成功update命令返回的示例文档:

{
"ok" : 1,
"nModified" : 0,
"n" : 1,
"upserted" : [
{
"index" : 0,
"_id" : ObjectId("52ccb2118908ccd753d65882")
}
]
}

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:以下是为涉及三个更新语句的批量更新返回的示例文档,其中一个更新语句成功,另外两个更新语句遇到错误:

{
"ok" : 1,
"nModified" : 1,
"n" : 1,
"writeErrors" : [
{
"index" : 1,
"code" : 16837,
"errmsg" : "The _id field cannot be changed from {_id: 1.0} to {_id: 5.0}."
},
{
"index" : 2,
"code" : 16837,
"errmsg" : "The _id field cannot be changed from {_id: 2.0} to {_id: 6.0}."
},
]
}