db.collection.update()
On this page本页内容
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
以更新与查询条件匹配的所有文档。
Syntax语法
Changed in version 5.05.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>, // Added in MongoDB 4.2
let: <document> // Added in MongoDB 5.0
}
)
Parameters参数
The db.collection.update()
method takes the following parameters:db.collection.update()
方法采用以下参数:
query | document | find() method are available.find() 方法中相同的查询选择器。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将拒绝插入新文档。 | ||||||||
update | document or pipeline |
| ||||||||
upsert | boolean | true , update() either:true 时,update() :
upsert and multi are true and no documents match the query, the update operation inserts only a single document.upsert 和multi 都为true ,并且没有与查询匹配的文档,则更新操作仅插入单个文档。query field(s) are uniquely indexed. query 字段的索引是唯一的。false , which does not insert a new document when no match is found. false ,在找不到匹配项时不插入新文档。 | ||||||||
multi | boolean | true , updates multiple documents that meet the query criteria. true ,则更新符合query 条件的多个文档。false , updates one document. The default value is false . For additional information, see Update Multiple Documents Examples. false ,则更新一个文档。默认值为false 。有关其他信息,请参阅更新多个文档示例。 | ||||||||
writeConcern | document | w: 1 .w:1 。writeConcern , see Override Default Write Concern. writeConcern 的示例,请参阅覆盖默认写入关注。 | ||||||||
collation | document | collation 允许用户为字符串比较指定特定于语言的规则,例如大小写和重音标记的规则。collation , see Specify Collation. collation 的示例,请参阅指定排序规则。 | ||||||||
arrayFilters | array | $[<identifier>] to define an identifier to update only those array elements that match the corresponding filter document in the arrayFilters . $[<identifier>] 定义一个标识符,以便仅更新那些与arrayFilters 中相应筛选器文档匹配的数组元素。Note arrayFilters for Array Update Operations.arrayFilters 。 | ||||||||
hint | Document or string | hint for Update Operations. hint 。 | ||||||||
let | document | { <variable_name_1>: <expression_1>, $$ ) together with your variable name in the form $$<variable_name> . $$ )和形式为$$<variable_name> 的变量名。$$targetTotal . $$targetTotal 。Note let and variables, see Use Variables in let .let 和变量的完整示例,请参阅在let 中使用变量。 |
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行为
Using $expr
in an Update with Upsert
在带有Upsert
的更新中使用$expr
$expr
in an Update with Upsert
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).multi:false
的db.collection.update()
,必须在_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()
可以针对多个分片。
See also: 另请参阅:
Replace Document Operations on a Sharded Collection替换分片集合上的文档操作
Starting in MongoDB 4.2, replace document operations attempt to target a single shard, first by using the query filter. 从MongoDB 4.2开始,替换文档操作尝试针对单个分片,首先使用查询筛选器。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
upsert
on a Sharded CollectionFor 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 (starting in MongoDB 4.2).对于替换文档操作(从MongoDB 4.2开始)。
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
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 从MongoDB 4.2开始,您可以更新文档的分片-key值,除非分片-key字段是不可变的_id
field. _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 要使用db.collection.update()
:db.collection.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.必须在完整的分片键上包含一个相等查询筛选器。
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 要使用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:此外,以下要求也适用:
null null |
|
null valuenull 值 |
|
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事务
db.collection.update()
can be used inside multi-document transactions.可以在多文档事务中使用。
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, 具体来说,在MongoDB 4.4及更高版本中,带有db.collection.update()
with upsert: true
can be run on an existing collection or a non-existing collection. upsert:true
的db.collection.update()
可以在现有集合或不存在的集合上运行。If 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及更早版本中,操作必须在现有集合上运行。
See also: 另请参阅:
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实例
The following tabs showcase a variety of common 以下选项卡展示了各种常见的update()
operations.update()
操作。
In 在mongosh
, create a books
collection which contains the following documents. mongosh
中,创建一个包含以下文档的books
集合。This command first removes all previously existing documents from the 此命令首先从books
collection: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
}
]);
Use Update Operator Expressions ($inc
and $set
)使用更新运算符表达式($inc
和$set
)
$inc
and $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>
文档必须仅包含更新运算符表达式。 -
Thedb.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 thestock
field, and$inc
运算符递增stock
字段,并且 -
the$set
operator replaces the value of the$set
运算符替换-
item
field,字段 -
publisher
field in theinfo
embedded document,info
嵌入文档中的publisher
字段, -
tags
field, and字段,以及 -
second element in theratings
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 had matched multiple documents, this operation would only update one matching document. query
参数匹配了多个文档,则此操作将只更新一个匹配的文档。To update multiple documents, you must set the 若要更新多个文档,必须将multi
option to true
.multi
选项设置为true
。
See also: 另请参阅:
$set
, $inc
, update operators dot notation$set
,$inc
,更新运算符点表示法
Push Elements to Existing Array ($push
)将元素推送到现有数组($push
)
$push
)The following operation uses the 以下操作使用$push
update operator to append a new object to the ratings
array.$push
更新运算符将一个新对象附加到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
}
See also: 另请参阅:
Remove Fields ($unset
)删除字段($unset
)
$unset
)The following operation uses the 以下操作使用$unset
operator to remove the tags
field from the document with { _id: 1 }
.$unset
运算符从具有{ _id: 1 }
的文档中删除tags
字段。
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
$unset
类似于以下SQL命令,该命令从books
表中删除tags
字段:
ALTER TABLE books
DROP COLUMN tags
See also: 另请参阅:
Update Multiple Documents ($update
With multi
)更新多个文档($Update
配合multi
)
$update
With multi
)If 如果multi
is set to true
, the db.collection.update()
method updates all documents that meet the <query>
criteria. multi
设置为true
,则db.collection.update()
方法会更新所有符合<query>
条件的文档。The multi
update operation may interleave with other read/write operations.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
字段设置为true
。If 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
See also: 另请参阅:
Insert a New Document if No Match Exists (Upsert
)如果不存在匹配项,则插入新文档(Upsert
)
Upsert
)When you specify the option upsert: true:当您指定选项upsert: true
时:
If document(s) match the query criteria,如果文档符合查询条件,db.collection.update()
performs an update.db.collection.update()
将执行更新。If no document matches the query criteria,如果没有文档符合查询条件,db.collection.update()
inserts a single document.db.collection.update()
将插入一个文档。NoteIf multiple, identical upserts are issued at roughly the same time, it is possible for如果在大致相同的时间发布多个相同的upsert,那么update()
used with upsert: true to create duplicate documents.update()
与upsert: true
一起使用可以创建重复的文档。See Upsert with Unique Index for more information.有关详细信息,请参阅具有唯一索引的Upsert。
If you specify 如果在分片集合上指定upsert: true
on a sharded collection, you must include the full shard key in the filter
. upsert:true
,则必须在筛选器中包含完整的分片键。For additional 有关分片化集合上的其他db.collection.update()
behavior on a sharded collection, see Sharded Collections.db.collection.update()
行为,请参阅分片集合。
The following tabs showcase a variety of uses of the 以下选项卡展示了upsert
modifier with update()
.upsert
修饰符与update()
的各种用法。
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 generations会添加带有随机生成的ObjectId值的_id
字段。NoteYou 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
:upsert
选项设置为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
字段创建一个新的唯一ObjectId
。You can see the 您可以在操作的WriteResult中看到反映的upsert
reflected in the WriteResult of the operation: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" ]
}
Upsert with Operator Expressions ($set
)与运算符表达式混淆($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
}
See also: 另请参阅:
Upsert using an Aggregation Pipeline使用聚合管道的Upsert
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")
}
See also: 另请参阅:
For additional examples of updates using aggregation pipelines, see Update with Aggregation Pipeline.有关使用聚合管道更新的其他示例,请参阅使用聚合管道进行更新。
Using upsert
with multi
(Match)将upsert
与multi
一起使用(Match)
upsert
with multi
(Match)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. multi
和upsert
选项。If matching documents exist, the operation updates all matching documents. If no matching documents exist, the operation inserts a new document.如果存在匹配的文档,则操作会更新所有匹配的文档。如果不存在匹配的文档,则操作将插入一个新文档。
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)将upsert
与multi
一起使用(无匹配)
upsert
with multi
(No Match)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. <query>
和<update>
规范中的字段插入单个文档。For example, consider the following operation:例如,考虑以下操作:
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" ]
}
Upsert with Dotted _id
Query使用点_id
查询进行Upsert
_id
QueryWhen 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. 如果您试图以这种方式插入文档,MongoDB将引发一个错误。For example, consider the following update operation. 例如,考虑以下更新操作。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"
}
})
See also: 另请参阅:
Upsert with Unique Index独特索引颠覆
When using the upsert: true option with the 当在update()
method, and not using a unique index on the query field(s), multiple instances of a 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.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
的文档。
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. update()
操作会更新这个新文档,请在name
字段上创建一个唯一索引。This guarantees that only one document with 这保证了集合中只允许一个name: Andy
is permitted in the collection.name: Andy
的文档。
With this unique index in place, the multiple c 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 thescore
value.update()
操作都会更新新插入的文档,从而增加score
值。
See also: 另请参阅:
Update with Aggregation Pipeline使用聚合管道更新
Starting in MongoDB 4.2, the 从MongoDB 4.2开始,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:管道可由以下阶段组成:
$addFields
and its alias及其别名$set
$project
and its alias及其别名$unset
$replaceRoot
and its alias及其别名$replaceWith
.
Using the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).使用聚合管道可以实现更具表达力的更新语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。
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:commentsSemester1
和commentsSomester2
字段分开,而是想将它们聚集到一个新的comments
字段中。以下更新操作使用聚合管道:
add the new添加新的comments
field and set thelastUpdate
field.comments
字段并设置lastUpdate
字段。remove the删除集合中所有文档的commentsSemester1
andcommentsSemester2
fields for all documents in the collection.commentsSemester1
和commentsSomester2
字段。
db.members.update(
{ },
[
{ $set: { comments: [ "$commentsSemester1", "$commentsSemester2" ], lastUpdate: "$$NOW" } },
{ $unset: [ "commentsSemester1", "commentsSemester2" ] }
],
{ multi: true }
)
First Stage第一阶段-
creates a new array field创建一个新的数组字段comments
whose elements are the current content of thecommentsSemester1
andcommentsSemester2
fields andcomments
,其元素是commentsSemester1
和commentsSomester2
字段的当前内容sets the field将字段lastUpdate
to the value of the aggregation variableNOW
.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 thecommentsSemester1
andcommentsSemester2
fields.$unset
阶段删除commentsSemester1
和commentsSemoster2
字段。
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" ] }
See also: 另请参阅:
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 }
)
First Stage第一阶段-
calculates a new field基于average
based on the average of thetests
field. See$avg
for more information on the$avg
aggregation operator and$trunc
for more information on the$trunc
truncate aggregation operator.tests
字段的average
来计算新的字段average
。有关$avg
聚合运算符的详细信息,请参阅$avg
;有关$trunc
截断聚合运算符的更多信息,请参阅$trunc
。sets the field将字段lastUpdate
to the value of the aggregation variableNOW
. The aggregation variableNOW
resolves to the current datetime value and remains the same throughout the pipeline.lastUpdate
设置为聚合变量NOW
的值。聚合变量NOW
解析为当前日期时间值,并在整个管道中保持不变。To access aggregation variables, prefix the variable with double dollar signs要访问聚合变量,请在变量前面加上双美元符号$$
and enclose in quotes.$$
并用引号括起来。
Second Stage第二阶段The$set
stage calculates a new fieldgrade
based on theaverage
field calculated in the previous stage. See$switch
for more information on the$switch
aggregation operator.$set
阶段根据上一阶段中计算的average
字段来计算新的字段grade
。有关$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" }
See also: 另请参阅:
Specify arrayFilters
for Array Update Operations为数组更新操作指定arrayFilters
arrayFilters
for Array Update OperationsIn 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
(可能多次),则不能为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 } }
]
arrayFilters
is not available for updates that use an aggregation pipeline.不可用于使用聚合管道的更新。
Update Elements Match arrayFilters
Criteria更新匹配arrayFilters
条件的元素
arrayFilters
CriteriaTo 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
的所有元素,请将已筛选的位置运算符$[<identifier>]
配合arrayFilters
选项一起使用:
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
数组中grade
大于或等于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
hint
for Update OperationsNew in version 4.2. 4.2版新增。
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
)
If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作将出错。
The update command returns the following:更新命令返回以下内容:
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 let
在let
中使用变量
let
New in version 5.0. 5.0版新增。
To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他地方访问的变量,请使用let
选项。
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
中定义targetFlavor
和newFlavor
变量,并使用这些变量将蛋糕口味从樱桃改为橙味:
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. w:2
,wtimeout
为5000毫秒。This operation either returns after the write propagates to both the primary and one secondary, or times out after 5 seconds.此操作要么在写入传播到主和一个辅助后返回,要么在5秒后超时。
db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{
multi: true,
writeConcern: { w: 2, wtimeout: 5000 }
}
)
Specify Collation指定排序规则
Specifies the collation to use for the operation.指定要用于操作的collation
。
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:collation
选项,并将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
字段:
Changed in version 4.44.4版更改.
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
的可能值:
clientSupplied | |
customDefault | setDefaultRWConcern .setDefaultRWConcern 。 |
getLastErrorDefaults | settings.getLastErrorDefaults field.settings.getLastErrorDefaults 字段。 |
implicitDefault |
See also: 另请参阅:
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"
}
})