Database Manual / Reference / mongosh Methods / Collections

db.collection.update() (mongosh method方法)

Important

Deprecated mongosh Method弃用的mongosh方法

This method is deprecated in mongosh. For alternative methods, see Compatibility Changes with Legacy mongo Shell.mongosh中已弃用此方法。有关替代方法,请参阅与旧版mongo Shell的兼容性更改。

Definition定义

db.collection.update(query, update, options)

Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.修改集合中的一个或多个现有文档。该方法可以根据更新参数修改现有文档的特定字段或完全替换现有文档。

By default, the db.collection.update() method updates a single document. Include the option multi: true to update all documents that match the query criteria.默认情况下,db.collection.update()方法更新单个文档。包含选项multi:true以更新符合查询条件的所有文档。

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

Changed in version 5.0.在版本5.0中的更改。

The db.collection.update() method has the following form:db.collection.update()方法具有以下形式:

db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>,
let: <document>,
maxTimeMS: <int>,
bypassDocumentValidation: <boolean>
}
)

Parameters参数

The db.collection.update() method takes the following parameters:db.collection.update()方法接受以下参数:

Parameter参数Type类型Description描述
querydocument文档

The selection criteria for the update. The same query selectors as in the find() method are available.更新的选择标准。可以使用与find()方法中相同的查询选择器

When you execute an update() with upsert: true and the query matches no existing document, MongoDB will refuse to insert a new document if the query specifies conditions on the _id field using dot notation.当您使用upsert:true执行update()并且查询与现有文档不匹配时,如果查询使用点符号_id字段上指定条件,MongoDB将拒绝插入新文档。

updatedocument or pipeline文件或管道

The modifications to apply. Can be one of the following:要应用的修改。可以是以下之一:

Update document更新文档

Contains only update operator expressions.仅包含更新运算符表达式

Replacement document替换文件

Contains only <field1>: <value1> pairs.仅包含<field1>: <value1>对。

Aggregation pipeline聚合管道

Contains only the following aggregation stages:仅包含以下聚合阶段:

For details and examples, see Oplog Entries.有关详细信息和示例,请参阅Oplog条目

upsertboolean布尔值

Optional. 可选。When true, update() either:当为true时,update()可以是:

  • Creates a new document if no documents match the query. For more details see upsert behavior.如果没有与query匹配的文档,则创建新文档。有关更多详细信息,请参阅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都为真,并且没有文档与查询匹配,则更新操作只插入一个文档。

To avoid multiple upserts, ensure that the query field(s) are uniquely indexed. See Upsert with Duplicate Values for an example.为避免多个upsert,请确保query字段具有唯一索引。有关示例,请参阅带有重复值的Upsert

Defaults to false, which does not insert a new document when no match is found.默认为false,当未找到匹配项时,不会插入新文档。

multiboolean布尔值

Optional. 可选。If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false. 如果设置为true,则更新符合查询条件的多个文档。如果设置为false,则更新一个文档。默认值为falseFor additional information, see Update Multiple Documents Examples.有关更多信息,请参阅更新多个文档示例

writeConcerndocument文档

Optional. 可选。A document expressing the write concern. Omit to use the default write concern w: "majority".表达写入关注的文件。省略使用默认的写关注w: "majority"

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

For an example using writeConcern, see Override Default Write Concern.有关使用writeConcern的示例,请参阅覆盖默认写关注

collationdocument文档

Optional.可选。

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音标记的规则。

For an example using collation, see Specify Collation.有关使用collation的示例,请参阅指定排序规则

arrayFiltersarray数组

Optional. 可选。An array of filter documents that determine which array elements to modify for an update operation on an array field.一组筛选文档,用于确定在数组字段上进行更新操作时要修改哪些数组元素。

In the update document, use the $[<identifier>] to define an identifier to update only those array elements that match the corresponding filter document in the arrayFilters.更新文档中,使用$[<identifier>]定义一个标识符,仅更新与arrayFilters中相应筛选器文档匹配的数组元素。

You cannot have an array filter document for an identifier if the identifier is not included in the update document.如果标识符未包含在更新文档中,则无法为标识符创建数组筛选器文档。

For examples, see Specify arrayFilters for Array Update Operations.有关示例,请参阅为数组更新操作指定arrayFilters

hintDocument or string文档或字符串

Optional. 可选。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

letdocument文档

Optional.可选。

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>. For example: $$targetTotal.要在命令中访问变量的值,请使用双美元符号前缀($$)和变量名,格式为$$<variable_name>。例如:$$targetTotal

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.有关使用let和变量的完整示例,请参阅let中使用变量

maxTimeMSinteger整数

Optional. 可选。Specifies the time limit in milliseconds for the update operation to run before timing out.指定在超时之前运行更新操作的时间限制(以毫秒为单位)。

bypassDocumentValidationboolean布尔值

Optional. 可选。Enables insert to bypass schema validation during the operation. This lets you insert documents that do not meet the validation requirements.启用insert以在操作期间绕过架构验证。这允许您插入不符合验证要求的文档。

Returns

The method returns a WriteResult document that contains the status of the operation.该方法返回一个包含操作状态的WriteResult文档。

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) if the operation results in an upsert.如果操作导致upsert,请在指定的集合上insert操作。

The built-in role readWrite provides the required privileges.内置角色readWrite提供了所需的权限。

Behavior行为

Limitations局限性

If you set multi: true, use the update() method only for idempotent operations.如果设置multi:true,则只对幂等运算使用update()方法。

Using $expr in an Update with UpsertUpsert更新中使用$expr

Attempting to use the $expr operator with the upsert flag set to true will generate an error.尝试在upsert标志设置为true的情况下使用$expr运算符将生成错误。

Sharded Collections分片化集合

To use db.collection.update() with multi: false on a sharded collection, you must include an exact match on the _id field or target a single shard (such as by including the shard key).要在分片集合上使用db.collection.update()multi:false,您必须在_id字段中包含一个完全匹配的项,或者以单个分片为目标(例如通过包含分片键)。

When the db.collection.update() performs update operations (and not document replacement operations), db.collection.update() can target multiple shards.db.collection.update()执行更新操作(而不是文档替换操作)时,db.collection.update()可以针对多个分片。

Replace Document Operations on a Sharded Collection替换分片集合上的文档操作

Replace document operations attempt to target a single shard, first by using the query filter. 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.在早期版本中,该操作尝试使用替换文档作为目标。

upsert on a Sharded Collection分片集合的upsert

For a db.collection.update() operation that includes upsert: true and is on a sharded collection, you must include the full shard key in the filter:对于包含upsert: true且位于分片集合上的db.collection.update()操作,您必须在筛选器中包含完整的分片键:

  • For an update operation.用于更新操作。
  • For a replace document operation.用于替换文档操作。

However, 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:要针对缺少分片键的文档,您可以将null相等匹配与另一个筛选条件结合使用(例如在_id字段上)。例如:

{ _id: <value>, <shardkeyfield>: null } // _id of the document missing shard key

Shard Key Modification分片键修改

You can update a document's shard key value unless the shard key field is the immutable _id field.您可以更新文档的分片键值,除非分片键字段是不可变的_id字段。

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

  • You must run on a mongos. Do not issue the operation directly on the shard.必须在mongos上运行。不要直接在分片上执行操作。
  • 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值键值,请酌情包含其他查询条件(例如在_id字段上)。

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

Missing Shard Key缺少分片钥匙

Documents in a sharded collection can be missing the shard key fields. 分片集合中的文档可能缺少分片键字段To use db.collection.update() to set the document's missing shard key, you must run on a mongos. 要使用db.collection.update()设置文档缺少的分片键,您必须在mongos上运行。Do not issue the operation directly on the shard.不要直接在分片上执行操作。

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.如果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.
  • 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值键值,请酌情包含其他查询条件(例如在_id字段上)。

See also:另请参阅:

Transactions事务

db.collection.update() can be used inside distributed transactions.可以在分布式事务中使用。

Important

In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed 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 distributed transactions.对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续是数据和用例的最佳选择。也就是说,对于许多场景,适当地对数据进行建模将最大限度地减少对分布式事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),另请参阅生产注意事项

Upsert within Transactions事务中的失误

You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.如果分布式事务不是跨分片写入事务,则可以在该事务内创建集合和索引。

db.collection.update() with upsert: true can be run on an existing collection or a non-existing collection. If run on a non-existing collection, the operation creates the collection.db.collection.update()配合upsert: true可以在现有集合或不存在的集合上运行。如果在不存在的集合上运行,则该操作将创建该集合。

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.要对事务使用写关注,请参阅事务和写关注

Oplog Entries操作日志条目

If a db.collection.update() operation successfully updates one or more documents, the operation adds an entry on the oplog (operations log). If the operation fails or does not find any documents to update, the operation does not add an entry on the oplog.如果db.collection.update()操作成功更新了一个或多个文档,则该操作会在oplog(操作日志)上添加一个条目。如果操作失败或找不到任何要更新的文档,则操作不会在oplog上添加条目。

Examples示例

The following tabs showcase a variety of common update() operations.以下选项卡展示了各种常见的update()操作。

In mongosh, create a books collection which contains the following documents. This command first removes all previously existing documents from the books collection:mongosh中,创建一个包含以下文档的books集合。此命令首先从books集合中删除所有以前存在的文档:

db.books.remove({});

db.books.insertMany([
{
"_id" : 1,
"item" : "TBD",
"stock" : 0,
"info" : { "publisher" : "1111", "pages" : 430 },
"tags" : [ "technology", "computer" ],
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
"reorder" : false
},
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 15,
"info" : { "publisher" : "5555", "pages" : 150 },
"tags" : [ ],
"ratings" : [ { "by" : "xyz", "rating" : 5 } ],
"reorder" : false
}
]);
Set

Use Update Operator Expressions ($inc and $set)使用更新运算符表达式($inc$set

If the <update> document contains update operator modifiers, such as those using the $set modifier, then:如果<update>文档包含更新运算符修饰符,例如使用$set修饰符的修饰符,那么:

  • The <update> document must contain only update operator expressions.<update>文档必须仅包含更新运算符表达式。

  • The db.collection.update() method updates only the corresponding fields in the document.db.collection.update()方法仅更新文档中的相应字段。

    • To update an embedded document or an array as a whole, specify the replacement value for the field.要更新嵌入文档或整个数组,请指定字段的替换值。
    • To update particular fields in an embedded document or in an array, use dot notation to specify the field.要更新嵌入式文档或数组中的特定字段,请使用点符号指定字段。
db.books.update(
{ _id: 1 },
{
$inc: { stock: 5 },
$set: {
item: "ABC123",
"info.publisher": "2222",
tags: [ "software" ],
"ratings.1": { by: "xyz", rating: 3 }
}
}
)

In this operation:在此操作中:

  • The <query> parameter of { _id: 1 } specifies which document to update,{ _id: 1 }<query>参数指定要更新的文档,
  • the $inc operator increments the stock field, and$inc运算符递增stock字段,并且
  • the $set operator replaces the value of the$set运算符替换了

    • item field,字段,
    • publisher field in the info embedded document,info文档中的publisher字段,
    • tags field, and字段,以及
    • second element in the ratings array.ratings数组中的第二个元素。

The updated document is the following:更新后的文件如下:

{
"_id" : 1,
"item" : "ABC123",
"stock" : 5,
"info" : { "publisher" : "2222", "pages" : 430 },
"tags" : [ "software" ],

"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
"reorder" : false
}

This operation corresponds to the following SQL statement:此操作对应于以下SQL语句:

UPDATE books
SET stock = stock + 5
item = "ABC123"
publisher = 2222
pages = 430
tags = "software"
rating_authors = "ijk,xyz"
rating_values = "4,3"
WHERE _id = 1

If the query parameter matches multiple documents, the operation only updates one matching document. To update multiple documents, set the multi option to true.如果query参数匹配多个文档,则操作只更新一个匹配的文档。要更新多个文档,请将multi选项设置为true

Arrays

Push Elements to Existing Array ($push)将元素推送到现有数组($Push

The following operation uses the $push update operator to append a new object to the ratings array.以下操作使用$push-update运算符将新对象附加到ratings数组中。

db.books.update(
{ _id: 2 },
{
$push: { ratings: { "by" : "jkl", "rating" : 2 } }
}
)

The updated document is the following:更新后的文件如下:

{
"_id" : 2,
"item" : "XYZ123",
"stock" : 15,
"info" : {
"publisher" : "5555",
"pages" : 150
},
"tags" : [ ],
"ratings" : [
{ "by" : "xyz", "rating" : 5 },
{ "by" : "jkl", "rating" : 2 }
],
"reorder" : false
}

Tip

$push

Unset

Remove Fields ($unset)删除字段($unset

The following operation uses the $unset operator to remove the tags field from the document with { _id: 1 }.以下操作使用$unset运算符从具有{ _id: 1 }的文档中删除标签字段。

db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )

The updated document is the following:更新后的文件如下:

{
"_id" : 1,
"item" : "TBD",
"stock" : 0,
"info" : {
"publisher" : "1111",
"pages" : 430
},
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
"reorder" : false
}

There is not a direct SQL equivalent to $unset, however $unset is similar to the following SQL command which removes the tags field from the books table:没有与$unset等效的直接SQL,但是$unset类似于以下SQL命令,该命令从books表中删除tags字段:

ALTER TABLE books
DROP COLUMN tags
Multiple

Update Multiple Documents ($update With multi)更新多个文档($Update配合multi

If multi is set to true, the db.collection.update() method updates all documents that meet the <query> criteria. The multi update operation may interleave with other read/write operations.如果multi设置为truedbcollectionupdate()方法将更新所有符合<query>条件的文档。multi更新操作可能会与其他读/写操作交错进行。

The following operation sets the reorder field to true for all documents where stock is less than or equal to 10. 以下操作将stock小于或等于10的所有文档的reorder字段设置为trueIf the reorder field does not exist in the matching document(s), the $set operator adds the field with the specified value.如果匹配文档中不存在reorder字段,则$set运算符将添加具有指定值的字段。

db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{ multi: true }
)

The resulting documents in the collection are the following:集合到的文件如下:

[
{
"_id" : 1,
"item" : "ABC123",
"stock" : 5,
"info" : {
"publisher" : "2222",
"pages" : 430
},
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
"reorder" : true
}
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 10,
"info" : { "publisher" : "2255", "pages" : 150 },
"tags" : [ "baking", "cooking" ],
"reorder" : true
}
]

This operation corresponds to the following SQL statement:此操作对应于以下SQL语句:

UPDATE books
SET reorder=true
WHERE stock <= 10

You cannot specify multi: true when performing a replacement and the update document contains only field:value expressions.执行替换时不能指定multi: true,并且更新文档仅包含field:value表达式。

Tip

$set

Insert a New Document if No Match Exists (Upsert)如果不存在匹配项,则插入新文档(Upsert

When you specify the option upsert: true:当您指定选项upsert:true时:

If you specify upsert: true on a sharded collection, you must include the full shard key in the filter. For additional db.collection.update() behavior on a sharded collection, see Sharded Collections.如果在分片集合上指定upsert: true,则必须在filter中包含完整的分片键。有关分片集合上的其他db.collection.update()行为,请参阅分片集合。

The following tabs showcase a variety of uses of the upsert modifier with update().以下选项卡展示了使用update()upsert修饰符的各种用法。

Replace

Upsert with Replacement Document替换文件

If no document matches the query criteria and the <update> parameter is a replacement document (i.e., contains only field and value pairs), the update inserts a new document with the fields and values of the replacement document.如果没有文档符合查询条件,并且<update>参数是替换文档(即仅包含字段和值对),则更新将插入一个包含替换文档的字段和值的新文档。

  • If you specify an _id field in either the query parameter or replacement document, MongoDB uses that _id field in the inserted document.如果在查询参数或替换文档中指定_id字段,MongoDB将在插入的文档中使用该_id字段。
  • If you do not specify an _id field in either the query parameter or replacement document, MongoDB generates adds the _id field with a randomly generated ObjectId value.如果您在查询参数或替换文档中都没有指定_id字段,MongoDB会生成一个随机生成的ObjectId值来添加_id字段。

    You cannot specify different _id field values in the query parameter and replacement document. If you do, the operation errors.您不能在查询参数和替换文档中指定不同的_id字段值。如果这样做,操作会出错。

For example, the following update sets the upsert option to true:例如,以下更新将upstert选项设置为true

db.books.update(
{ item: "ZZZ135" }, // Query parameter
{ $set:
{
item: "ZZZ135", stock: 5, tags: [ "database" ] // Replacement document
}
},
{ upsert: true } // Options
)

If no document matches the <query> parameter, the update operation inserts a document with only the replacement document. 如果没有文档与<query>参数匹配,则更新操作将插入一个仅包含替换文档的文档。Because no _id field was specified in the replacement document or query document, the operation creates a new unique ObjectId for the new document's _id field. 由于替换文档或查询文档中没有指定_id字段,因此该操作为新文档的_id字段创建了一个新的唯一ObjectIdYou can see the upsert reflected in the WriteResult of the operation:您可以在操作的WriteResult中看到反映的upsert

WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5da78973835b2f1c75347a83")
})

The operation inserts the following document into the books collection (your ObjectId value will differ):该操作将以下文档插入books集合中(ObjectId值将不同):

{
"_id" : ObjectId("5da78973835b2f1c75347a83"),
"item" : "ZZZ135",
"stock" : 5,
"tags" : [ "database" ]
}
Set

Upsert with Operator Expressions ($set)运算符表达式($set)的更新

If no document matches the query criteria and the <update> parameter is a document with update operator expressions, then the operation creates a base document from the equality clauses in the <query> parameter and applies the expressions from the <update> parameter.如果没有文档与查询条件匹配,并且<update>参数是一个具有更新运算符表达式的文档,则该操作将根据<query>参数中的相等子句创建一个基文档,并应用<update>变量中的表达式。

Comparison operations from the <query> will not be included in the new document. 来自<query>比较操作将不会包含在新文档中。If the new document does not include the _id field, MongoDB adds the _id field with an ObjectId value.如果新文档不包含_id字段,MongoDB会添加具有ObjectId值的_id字段。

For example, the following update sets the upsert option to true:例如,以下更新将upsert选项设置为true

db.books.update(
{ item: "BLP921" }, // Query parameter
{ // Update document
$set: { reorder: false },
$setOnInsert: { stock: 10 }
},
{ upsert: true } // Options
)

If no documents match the query condition, the operation inserts the following document (your ObjectId value will differ):如果没有符合查询条件的文档,则操作将插入以下文档(ObjectId值将不同):

{
"_id" : ObjectId("5da79019835b2f1c75348a0a"),
"item" : "BLP921",
"reorder" : false,
"stock" : 10
}
Aggregation

Upsert using an Aggregation Pipeline使用聚合管道进行升级

If the <update> parameter is an aggregation pipeline, the update creates a base document from the equality clauses in the <query> parameter, and then applies the pipeline to the document to create the document to insert. 如果<update>参数是聚合管道,则更新将从<query>参数中的相等子句创建一个基文档,然后将管道应用于文档以创建要插入的文档。If the new document does not include the _id field, MongoDB adds the _id field with an ObjectId value.如果新文档不包含_id字段,MongoDB会添加具有ObjectId值的_id字段。

For example, the following upsert: true operation specifies an aggregation pipeline that uses例如,以下upsert: true操作指定了一个聚合管道,该管道使用

  • the $replaceRoot stage which can provide somewhat similar behavior to a $setOnInsert update operator expression,$replaceRoot阶段可以提供与$setOnInsert更新运算符表达式有些相似的行为,
  • the $set stage which can provide similar behavior to the $set update operator expression,$set阶段可以提供与$set更新运算符表达式类似的行为,
  • the aggregation variable NOW, which resolves to the current datetime and can provide similar behavior to the $currentDate update operator expression.聚合变量NOW,它解析为当前日期时间,并可以提供与$currentDate更新运算符表达式类似的行为。
db.books.update(
{ item: "MRQ014", ratings: [2, 5, 3] }, // Query parameter
[ // Aggregation pipeline
{ $replaceRoot: { newRoot: { $mergeObjects: [ { stock: 0 }, "$$ROOT" ] } } },
{ $set: { avgRating: { $avg: "$ratings" }, tags: [ "fiction", "murder" ], lastModified: "$$NOW" } }
],
{ upsert: true } // Options
)

If no document matches the <query> parameter, the operation inserts the following document into the books collection (your ObjectId value will differ):如果没有文档与<query>参数匹配,则该操作会将以下文档插入到books集合中(ObjectId值将不同):

{
"_id" : ObjectId("5e2921e0b4c550aad59d1ba9"),
"stock" : 0,
"item" : "MRQ014",
"ratings" : [ 2, 5, 3 ],
"avgRating" : 3.3333333333333335,
"tags" : [ "fiction", "murder" ],
"lastModified" : ISODate("2020-01-23T04:32:32.951Z")
}

Tip

For additional examples of updates using aggregation pipelines, see Update with Aggregation Pipeline.有关使用聚合管道进行更新的其他示例,请参阅使用聚合管道更新

Multiple

Using upsert with multi (Match)使用upsertmulti(匹配)

From mongosh, insert the following documents into a books collection:mongosh中,将以下文档插入books集合中:

db.books.insertMany( [
{
_id: 5,
item: "RQM909",
stock: 18,
info: { publisher: "0000", pages: 170 },
reorder: true
},
{
_id: 6,
item: "EFG222",
stock: 15,
info: { publisher: "1111", pages: 72 },
reorder: true
}
] )

The following operation specifies both the multi option and the upsert option. If matching documents exist, the operation updates all matching documents. If no matching documents exist, the operation inserts a new document.以下操作指定了multi选项和upsert选项。如果存在匹配的文档,则操作会更新所有匹配的文档。如果不存在匹配的文档,则该操作将插入一个新文档。

db.books.update(
{ stock: { $gte: 10 } }, // Query parameter
{ // Update document
$set: { reorder: false, tags: [ "literature", "translated" ] }
},
{ upsert: true, multi: true } // Options
)

The operation updates all matching documents and results in the following:该操作将更新所有匹配的文档,并产生以下结果:

{
"_id" : 5,
"item" : "RQM909",
"stock" : 18,
"info" : { "publisher" : "0000", "pages" : 170 },
"reorder" : false,
"tags" : [ "literature", "translated" ]
}
{
"_id" : 6,
"item" : "EFG222",
"stock" : 15,
"info" : { "publisher" : "1111", "pages" : 72 },
"reorder" : false,
"tags" : [ "literature", "translated" ]
}

Using upsert with multi (No Match)使用带有multiupsert(不匹配)

If the collection had no matching document, the operation would result in the insertion of a single document using the fields from both the <query> and the <update> specifications. For example, consider the following operation:如果集合没有匹配的文档,则该操作将导致使用<query><update>规范中的字段插入单个文档。例如,考虑以下操作:

db.books.update(
{ "info.publisher": "Self-Published" }, // Query parameter
{ // Update document
$set: { reorder: false, tags: [ "literature", "hardcover" ], stock: 25 }
},
{ upsert: true, multi: true } // Options
)

The operation inserts the following document into the books collection (your ObjectId value will differ):该操作将以下文档插入books集合中(ObjectId值将不同):

{
"_id" : ObjectId("5db337934f670d584b6ca8e0"),
"info" : { "publisher" : "Self-Published" },
"reorder" : false,
"stock" : 25,
"tags" : [ "literature", "hardcover" ]
}
Dotted_id

Upsert with Dotted _id QueryUpsert使用加点的_id查询

When you execute an update() with upsert: true and the query matches no existing document, MongoDB will refuse to insert a new document if the query specifies conditions on the _id field using dot notation.当您使用upsert: true执行update()并且查询与现有文档不匹配时,如果查询使用点符号在_id字段上指定条件,MongoDB将拒绝插入新文档。

This restriction ensures that the order of fields embedded in the _id document is well-defined and not bound to the order specified in the query.此限制确保了_id文档中嵌入的字段顺序是明确定义的,并且不绑定到查询中指定的顺序。

If you attempt to insert a document in this way, MongoDB will raise an error. For example, consider the following update operation. 如果您尝试以这种方式插入文档,MongoDB将引发错误。例如,考虑以下更新操作。Since the update operation specifies upsert:true and the query specifies conditions on the _id field using dot notation, then the update will result in an error when constructing the document to insert.由于更新操作指定了upsert:true,查询使用点表示法指定了_id字段的条件,因此在构造要插入的文档时,更新将导致错误。

db.collection.update(
{ "_id.name": "Robert Frost", "_id.uid": 0 }, // Query parameter
{ $set:
{
"categories": [ "poet", "playwright" ] // Replacement document
}
},
{ upsert: true } // Options
)

The WriteResult of the operation returns the following error:操作的WriteResult返回以下错误:

WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 111,
"errmsg" : "field at '_id' must be exactly specified, field at sub-path '_id.name'found"
}
})

Upsert with Duplicate Values出现重复值

Upserts can create duplicate documents, unless there is a unique index to prevent duplicates.除非有唯一索引来防止重复,否则Upsert可以创建重复的文档。

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.people.update(
{ name: "Andy" },
{ $inc: { score: 1 } },
{
upsert: true,
multi: 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的文档。

A unique index on the name field ensures that only one document is created. With a unique index in place, the multiple update() operations now exhibit the following behavior:name字段上的唯一索引可确保只创建一个文档。有了唯一的索引,多个update()操作现在表现出以下行为:

  • Exactly one update() operation will successfully insert a new document.只需执行一次update()操作,即可成功插入新文档。
  • Other update() operations either update the newly-inserted document or fail due to a unique key collision.其他update()操作要么更新新插入的文档,要么由于唯一键冲突而失败。

    In order for other update() operations to update the newly-inserted document, all of the following conditions must be met:为了让其他update()操作更新新插入的文档,必须满足以下所有条件:

    • The target collection has a unique index that would cause a duplicate key error.目标集合具有唯一索引,这将导致重复键错误。
    • The update operation is not updateMany or multi is false.更新操作未updateManymultifalse
    • The update match condition is either:更新匹配条件为:

      • A single equality predicate. For example 一个等式谓词。例如{ "fieldA" : "valueA" }
      • A logical AND of equality predicates. For example 等式谓词的逻辑AND。例如{ "fieldA" : "valueA", "fieldB" : "valueB" }
    • The fields in the equality predicate match the fields in the unique index key pattern.相等谓词中的字段与唯一索引键模式中的字段匹配。
    • The update operation does not modify any fields in the unique index key pattern.更新操作不会修改唯一索引键模式中的任何字段。

The following table shows examples of upsert operations that, when a key collision occurs, either result in an update or fail.下表显示了当发生键冲突时,导致更新或失败的upsert操作示例。

Unique Index Key Pattern唯一索引键模式Update Operation更新操作Result结果
{ name : 1 }
db.people.updateOne(
{ name: "Andy" },
{ $inc: { score: 1 } },
{ upsert: true }
)
The score field of the matched document is incremented by 1.匹配文档的score字段递增1。
{ name : 1 }
db.people.updateOne(
{ name: { $ne: "Joe" } },
{ $set: { name: "Andy" } },
{ upsert: true }
)
The operation fails because it modifies the field in the unique index key pattern (name).操作失败,因为它修改了唯一索引键模式(name)中的字段。
{ name : 1 }
db.people.updateOne(
{ name: "Andy", email: "andy@xyz.com" },
{ $set: { active: false } },
{ upsert: true }
)
The operation fails because the equality predicate fields (name, email) do not match the index key field (name).操作失败,因为相等谓词字段(nameemail)与索引键字段(name)不匹配。

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

The db.collection.update() method can accept an aggregation pipeline [ <stage1>, <stage2>, ... ] that specifies the modifications to perform. db.collection.update()方法可以接受指定要执行的修改的聚合管道[ <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).使用聚合管道允许更具表现力的更新语句,例如基于当前字段值表示条件更新,或使用另一个字段的值更新一个字段。

Modify a Field Using the Values of the Other Fields in the Document使用文档中其他字段的值修改字段

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

db.students.insertMany( [
{ "_id" : 1, "student" : "Skye", "points" : 75, "commentsSemester1" : "great at math", "commentsSemester2" : "loses temper", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "students" : "Elizabeth", "points" : 60, "commentsSemester1" : "well behaved", "commentsSemester2" : "needs improvement", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }
] )

Assume that instead of separate commentsSemester1 and commentsSemester2 fields, you want to gather these into a new comments field. The following update operation uses an aggregation pipeline to:假设您不想将commentsSemester1commentsSemester2字段分开,而是想将它们集合到一个新的comments字段中。以下更新操作使用聚合管道来:

  • add the new comments field and set the lastUpdate field.添加新的comments字段并设置lastUpdate字段。
  • remove the commentsSemester1 and commentsSemester2 fields for all documents in the collection.删除集合中所有文档的commentsSemester1commentsSemester2字段。
db.members.update(
{ },
[
{ $set: { comments: [ "$commentsSemester1", "$commentsSemester2" ], lastUpdate: "$$NOW" } },
{ $unset: [ "commentsSemester1", "commentsSemester2" ] }
],
{ multi: true }
)

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

First Stage第一阶段

The $set stage:$set阶段:

  • creates a new array field comments whose elements are the current content of the commentsSemester1 and commentsSemester2 fields and创建一个新的数组字段comments,其元素是commentsSemester1commentsSemester2字段的当前内容,以及
  • sets the field lastUpdate to the value of the aggregation variable NOW. 将字段lastUpdate设置为聚合变量NOW的值。The aggregation variable NOW resolves to the current datetime value and remains the same throughout the pipeline. 聚合变量NOW解析为当前日期时间值,并在整个管道中保持不变。To access aggregation variables, prefix the variable with double dollar signs $$ and enclose in quotes.要访问聚合变量,请在变量前添加双美元符号$$并括在引号中。
Second Stage第二阶段
The $unset stage removes the commentsSemester1 and commentsSemester2 fields.$unset阶段删除commentsSemester1commentsSemester2字段。

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

{ "_id" : 1, "student" : "Skye", "status" : "Modified", "points" : 75, "lastUpdate" : ISODate("2020-01-23T05:11:45.784Z"), "comments" : [ "great at math", "loses temper" ] }
{ "_id" : 2, "student" : "Elizabeth", "status" : "Modified", "points" : 60, "lastUpdate" : ISODate("2020-01-23T05:11:45.784Z"), "comments" : [ "well behaved", "needs improvement" ] }

Perform Conditional Updates Based on Current Field Values根据当前字段值执行条件更新

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

db.students3.insertMany( [
{ "_id" : 1, "tests" : [ 95, 92, 90 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }
] )

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

db.students3.update(
{ },
[
{ $set: { average : { $trunc: [ { $avg: "$tests" }, 0 ] }, lastUpdate: "$$NOW" } },
{ $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 }
)

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:$set阶段:

  • calculates a new field average based on the average of the tests field. 基于tests字段的平均值计算新的字段averageSee $avg for more information on the $avg aggregation operator and $trunc for more information on the $trunc truncate aggregation operator.有关$avg聚合运算符的更多信息,请参阅$avg;有关$trunc截断聚合运算符的详细信息,请参阅$trunc
  • sets the field lastUpdate to the value of the aggregation variable NOW. 将字段lastUpdate设置为聚合变量NOW的值。The aggregation variable NOW resolves to the current datetime value and remains the same throughout the pipeline. 聚合变量NOW解析为当前日期时间值,并在整个管道中保持不变。To access aggregation variables, prefix the variable with double dollar signs $$ and enclose in quotes.要访问聚合变量,请在变量前添加双美元符号$$并括在引号中。
Second Stage第二阶段
The $set stage calculates a new field grade based on the average field calculated in the previous stage. $set阶段根据前一阶段计算的average字段计算新的字段gradeSee $switch for more information on the $switch aggregation operator.有关$switch聚合运算符的更多信息,请参阅$switch

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

{ "_id" : 1, "tests" : [ 95, 92, 90 ], "lastUpdate" : ISODate("2020-01-24T17:29:35.340Z"), "average" : 92, "grade" : "A" }
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "lastUpdate" : ISODate("2020-01-24T17:29:35.340Z"), "average" : 90, "grade" : "A" }
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "lastUpdate" : ISODate("2020-01-24T17:29:35.340Z"), "average" : 75, "grade" : "C" }

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

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.如果标识符未包含在更新文档中,则无法为标识符创建数组筛选器文档。

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:例如,如果更新语句包含标识符x(可能多次),则不能为包含2个单独的x筛选文档的arrayFilters指定以下内容:

// 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 } }
]

arrayFilters is not available for updates that use an aggregation pipeline.不适用于使用聚合管道的更新。

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

To update all array elements which match a specified criteria, use the arrayFilters parameter.要更新符合指定条件的所有数组元素,请使用arrayFilters参数。

In mongosh, create a students collection with the following documents:mongosh中,使用以下文档创建一个students集合:

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

To update 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的所有元素,请使用带arrayFilters选项的筛选位置运算符$[<identifier>]

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

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更新文档数组的特定元素

You can also use the arrayFilters parameter to update specific document fields within an array of documents.您还可以使用arrayFilters参数更新文档数组中的特定文档字段。

In mongosh, create a students2 collection with the following documents:mongosh中,使用以下文档创建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数组中等级大于或等于85的所有元素的mean字段的值,请将筛选后的位置运算符$[<identifier>]arrayFilters一起使用:

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

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

In mongosh, create a newStudents collection with the following documents:mongosh中,使用以下文档创建一个newStudents集合:

db.newStudents.insertMany( [
{ "_id" : 1, "student" : "Richard", "grade" : "F", "points" : 0, "comments1" : null, "comments2" : null },
{ "_id" : 2, "student" : "Jane", "grade" : "A", "points" : 60, "comments1" : "well behaved", "comments2" : "fantastic student" },
{ "_id" : 3, "student" : "Ronan", "grade" : "F", "points" : 0, "comments1" : null, "comments2" : null },
{ "_id" : 4, "student" : "Noah", "grade" : "D", "points" : 20, "comments1" : "needs improvement", "comments2" : null },
{ "_id" : 5, "student" : "Adam", "grade" : "F", "points" : 0, "comments1" : null, "comments2" : null },
{ "_id" : 6, "student" : "Henry", "grade" : "A", "points" : 86, "comments1" : "fantastic student", "comments2" : "well behaved" }
] )

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

db.newStudents.createIndex( { grade: 1 } )

The following update operation explicitly hints to use the index {grade: 1 }:以下更新操作明确提示使用索引{grade: 1 }

db.newStudents.update(
{ points: { $lte: 20 }, grade: "F" }, // Query parameter
{ $set: { comments1: "failed class" } }, // Update document
{ multi: true, hint: { grade: 1 } } // Options
)

Note

If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作会出错。

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

WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

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

db.newStudents.explain().update(
{ "points": { $lte: 20 }, "grade": "F" },
{ $set: { "comments1": "failed class" } },
{ multi: true, hint: { grade: 1 } }
)

The db.collection.explain().update() does not modify the documents.db.collection.explain().update()不会修改文档。

Use Variables in letlet中使用变量

New in version 5.0.在版本5.0中新增。

To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他地方访问的变量,请使用let选项。

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.cakeFlavors.update(
{ $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
[ { $set: { flavor: "$$newFlavor" } } ],
{ let : { targetFlavor: "cherry", newFlavor: "orange" } }
)

Override Default Write Concern覆盖默认写入关注

The following operation to a replica set specifies a write concern of w: 2 with a wtimeout of 5000 milliseconds. This operation either returns after the write propagates to both the primary and one secondary, or times out after 5 seconds.以下对副本集的操作指定了w:2wtimeout5000毫秒的写入关注。此操作要么在写入传播到主服务器和一个辅助服务器后返回,要么在5秒后超时。

db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{
multi: true,
writeConcern: { w: 2, wtimeout: 5000 }
}
)

Write Concern Errors in Sharded Clusters分片集群中的写入关注错误

Changed in version 8.1.2.在版本8.1.2中的更改。

When db.collection.update() executes on mongos in a sharded cluster, a writeConcernError is always reported in the response, even when one or more other errors occur. db.collection.update()在分片集群中的mongos上执行时,即使出现一个或多个其他错误,也总是在响应中报告writeConcernErrorIn previous releases, other errors sometimes caused db.collection.update() to not report write concern errors.在以前的版本中,其他错误有时会导致db.collection.update()不报告写入关注错误。

For example, if a document fails validation, triggering a DocumentValidationFailed error, and a write concern error also occurs, both the DocumentValidationFailed error and the writeConcernError are returned in the top-level field of the response.例如,如果文档验证失败,触发DocumentValidationFailed错误,并且还发生写入关注错误,则DocumentValidationFailure错误和writeConcernError都会在响应的顶级字段中返回。

Specify Collation指定排序规则

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: {
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.不能为操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一个排序规则,对排序使用另一个。

In mongosh, create a collection named myColl with the following documents:mongosh中,使用以下文档创建一个名为myColl的集合:

db.myColl.insertMany( [
{ _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 and sets multi to true to update all matching documents:以下操作包括排序规则选项,并将multi设置为true以更新所有匹配的文档:

db.myColl.update(
{ category: "cafe" },
{ $set: { status: "Updated" } },
{
collation: { locale: "fr", strength: 1 },
multi: true
}
)

The write result of the operation returns the following document, indicating that all three documents in the collection were updated:操作的写入结果返回以下文档,表示集合中的所有三个文档都已更新:

WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

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

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

WriteResult

Successful Results成功的结果

The db.collection.update() method returns a WriteResult() object that contains the status of the operation. db.collection.update()方法返回一个包含操作状态的WriteResult()对象。Upon success, the WriteResult() object contains the number of documents that matched the query condition, the number of documents inserted by the update, and the number of documents modified:成功后,WriteResult()对象包含与查询条件匹配的文档数、更新插入的文档数和修改的文档数:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Write Concern Errors写入关注错误

If the db.collection.update() method encounters write concern errors, the results include the WriteResult.writeConcernError field:如果db.collection.update()方法遇到写入关注错误,结果将包括WriteResult.writeConcernError字段:

WriteResult({
"nMatched" : 1,
"nUpserted" : 0,
"nModified" : 1,
"writeConcernError": {
"code" : 64,
"errmsg" : "waiting for replication timed out",
"errInfo" : {
"wtimeout" : true,
"writeConcern" : {
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})

The following table explains the possible values of WriteResult.writeConcernError.provenance:下表解释了WriteResult.writeConcernError.provenance的可能值:

Provenance来源Description描述
clientSuppliedThe write concern was specified in the application.应用程序中指定了写入关注。
customDefaultThe write concern originated from a custom defined default value. 写入关注源于自定义的默认值。See setDefaultRWConcern.请参阅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.在没有所有其他写入关注规范的情况下,写入关注源自服务器。

Errors Unrelated to Write Concern与书写入关注无关的错误

If the db.collection.update() method encounters a non-write concern error, the results include the WriteResult.writeError field:如果db.collection.update()方法遇到非写入关注错误,则结果包括WriteResult.writeError字段:

WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 7,
"errmsg" : "could not contact primary for replica set shard-a"
}
})