On this page本页内容
db.collection.
update
(query, update, options)¶mongo
Shell Method方法
This page documents the 此页面记录了mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. mongo
Shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。
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. db.collection.update()
方法更新单个文档。Include the option multi: true to update all documents that match the query criteria.包括选项multi:true
以更新与查询条件匹配的所有文档。
The db.collection.update()
method has the following form:db.collection.update()
方法具有以下形式:
The db.collection.update()
method takes the following parameters:db.collection.update()
方法采用以下参数:
query | document |
| ||||||
update | document or pipeline |
| ||||||
upsert | boolean |
| ||||||
multi | boolean |
| ||||||
writeConcern | document |
| ||||||
collation | document |
| ||||||
arrayFilters | array |
Note
| ||||||
hint |
|
The method returns a WriteResult document that contains the status of the operation.该方法返回包含操作状态的WriteResult
文档。
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
。
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()
可以针对多个分片。
See also参阅
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 Collectionupsert
¶For a 对于包含upsert: true且位于分片集合上的db.collection.update()
operation that includes upsert: true and is on a sharded collection, you must include the full shard key in the filter
:db.collection.update()
操作,必须在筛选器中包含完整的分片键:
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 要将缺少shard键的文档作为目标,可以将null
equality match in conjunction with another filter condition (such as on the _id
field). null
相等匹配与另一个筛选条件(例如在_id
字段上)结合使用。For example:例如:
Starting in MongoDB 4.2, you can update a document’s shard key value unless the shard key field is the immutable 从MongoDB 4.2开始,您可以更新文档的分片键值,除非分片键字段是不可变的_id
field. _id
字段。Before MongoDB 4.2, 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()
修改现有切分键值,请执行以下操作:
mongos
. mongos
上运行。multi: false
.multi:false
。Tip
Since a missing key value is returned as part of a null equality match, to avoid updating a null-valued key, include additional query conditions (such as on the 由于缺少的键值是作为空相等匹配的一部分返回的,为了避免更新空值键值,请酌情包括其他查询条件(例如在_id
field) as appropriate._id
字段上)。
See also upsert on a Sharded Collection.另请参见在分片集合上upsert。
Starting in version 4.4, documents in a sharded collection can be missing the shard key fields. 从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:此外,以下要求也适用:
To set to null |
|
null valuenull 值 |
|
Tip
Since a missing key value is returned as part of a null equality match, to avoid updating a null-valued key, include additional query conditions (such as on the 由于缺少的键值是作为空相等匹配的一部分返回的,为了避免更新空值键值,请酌情包括其他查询条件(例如在_id
field) as appropriate._id
字段上)。
See also:参阅:
db.collection.update()
can be used inside multi-document transactions.db.collection.update()
可以在多文档事务中使用。
Important重要的
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,而多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
Starting in MongoDB 4.4 with feature compatibility version (fcv) 从功能兼容版本(fcv)"4.4"
, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction."4.4"
的MongoDB 4.4开始,如果事务不是跨切分写入事务,则可以在多文档事务中创建集合和索引。
As such, for the feature compatibility version (fcv) is 因此,对于功能兼容性版本(fcv)为"4.4"
or greater, db.collection.update()
with upsert: true
can be run against an existing collection or a non-existing collection. "4.4"
或更高的版本,db.collection.update()
配合upsert:true
可以针对现有集合或不存在的集合运行。If run against a non-existing collection, the operation creates the collection.如果针对不存在的集合运行,该操作将创建该集合。
If the feature compatibility version (fcv) is 如果功能兼容版本(fcv)为“4.2”或更低,则操作必须针对现有集合。"4.2"
or less, the operation must be against an existing collection.
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.要将写关注点用于事务,请参阅事务和写关注点。
From the 从mongo
shell, create a books
collection which contains the following documents. mongo
shell创建一个包含以下文档的books
集合。This command first removes all previously existing documents from the 此命令首先从books
collection:books
集合中删除所有以前存在的文档:
If the 如果<update>
document contains update operator modifiers, such as those using the $set
modifier, then:<update>
文档包含update
运算符修饰符,例如使用$set
修饰符的修饰符,则:
<update>
document must contain only update operator expressions.<update>
文档必须仅包含更新运算符表达式。db.collection.update()
method updates only the corresponding fields in the document.db.collection.update()
方法只更新文档中相应的字段。You can use the web shell below to insert the sample documents and execute the example update operation:您可以使用下面的web shell插入示例文档并执行示例更新操作:
In this operation:在此操作中:
<query>
parameter of { _id: 1 }
specifies which document to update,<query>
参数{_id:1}指定要更新的文档,$inc
operator increments the stock
field, and$inc
运算符增加stock
字段,并且$set
operator replaces the value of the$set
运算符替换item
publisher
field in the info
embedded document,info
嵌入文档中的publisher
字段,tags
ratings
array.ratings
数组中的第二个元素。The updated document is the following:更新后的文件如下:
This operation corresponds to the following SQL statement:此操作对应于以下SQL语句:
Note
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参阅
From the 从mongo
shell, create a books
collection which contains the following documents. mongo
shell创建一个包含以下文档的books
集合。This command first removes all previously existing documents from the 此命令首先从books
collection:books
集合中删除所有以前存在的文档:
The following operation uses the 下面的操作使用$push
update operator to append a new object to the ratings
array.$push
更新运算符将一个新对象附加到ratings
数组。
You can use the web shell below to insert the sample documents and execute the example update operation:您可以使用下面的web shell插入示例文档并执行示例更新操作:
The updated document is the following:更新后的文件如下:
See also参阅
From the 从mongo
shell, create a books
collection which contains the following documents. mongo
shell创建一个包含以下文档的books
集合。This command first removes all previously existing documents from the 此命令首先从books
collection:books
集合中删除所有以前存在的文档:
The following operation uses the 以下操作使用$unset
operator to remove the tags
field from the document with { _id: 1 }
.$unset
运算符从带有{ _id: 1 }
的文档中删除标记字段。
You can use the web shell below to insert the sample documents and execute the example update operation:您可以使用下面的web shell插入示例文档并执行示例更新操作:
The updated document is the following:更新后的文件如下:
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
字段:
See also参阅
From the 从mongo
shell, create a books
collection which contains the following documents. mongo
shell创建一个包含以下文档的books
集合。This command first removes all previously existing documents from the 此命令首先从books
collection:books
集合中删除所有以前存在的文档:
If the 如果<update>
document contains only field:value
expressions, then:<update>
文档仅包含field:value
表达式,则:
db.collection.update()
method replaces the matching document with the <update>
document. db.collection.update()
方法将匹配的文档替换为<update>
文档。db.collection.update()
method does not replace the _id
value.db.collection.update()
方法不会替换_id
值。db.collection.update()
The following operation passes an 以下操作将传递一个只包含字段和值对的<update>
document that contains only field and value pairs. <update>
文档。The 除了<update>
document completely replaces the original document except for the _id
field._id
字段外,<update>
文档将完全替换原始文档。
You can use the web shell below to insert the sample documents and execute the example update operation:您可以使用下面的web shell插入示例文档并执行示例更新操作:
The updated document contains only the fields from the replacement document and the 更新后的文档仅包含替换文档和_id
field. _id
字段中的字段。As such, the fields 因此,由于这些字段不在替换文档中,更新文档中不再存在ratings
and reorder
no longer exist in the updated document since the fields were not in the replacement document.rating
和reorder
字段。
This operation corresponds to the following SQL statements:此操作对应于以下SQL语句:
From the 从mongo
shell, create a books
collection which contains the following documents. mongo
shell创建一个包含以下文档的books
集合。This command first removes all previously existing documents from the 此命令首先从books
collection:books
集合中删除所有以前存在的文档:
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
运算符将使用指定值添加该字段。
You can use the web shell below to insert the sample documents and execute the example update operation:您可以使用下面的web shell插入示例文档并执行示例更新操作:
The resulting documents in the collection are the following:集合中产生的文档如下所示:
This operation corresponds to the following SQL statement:此操作对应于以下SQL语句:
Note
You cannot specify 在执行替换时,即multi: true
when performing a replacement, i.e., when the <update> document contains only field:value
expressions.<update>
文档仅包含field:value
表达式时,不能指定multi:true
。
See also参阅
Upsert
)¶When you specify the option upsert: true:指定选项upsert:true
时:
db.collection.update()
performs an update.db.collection.update()
执行更新。db.collection.update()
inserts a single document.db.collection.update()
插入单个文档。If you specify 如果在分片集合上指定upsert: true
on a sharded collection, you must include the full shard key in the filter
. upsert:true
,则必须在filter
中包含完整的分片密钥。For additional 对于额外的db.collection.update()
behavior on a sharded collection, see Sharded Collections.db.collection.update()
在分片集合上的行为,请参阅分片集合。
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>
参数是替换文档(即,仅包含字段和值对),则更新会插入一个包含替换文档的字段和值的新文档。
_id
field in either the query parameter or replacement document, MongoDB uses that _id
field in the inserted document._id
字段,MongoDB将在插入的文档中使用该_id
字段。_id
field in either the query parameter or replacement document, MongoDB generates adds the _id
field with a randomly generated ObjectId value._id
字段,MongoDB会生成一个_id
字段,并使用随机生成的ObjectId值添加该字段。
Note
You cannot specify different 不能在查询参数和替换文档中指定不同的_id
field values in the query parameter and replacement document. _id
字段值。If you do, the operation errors.如果这样做,操作就会出错。
For example, the following update sets the upsert option to 例如,以下更新将upsert选项设置为true
:true
:
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
:
The operation inserts the following document into the 该操作将以下文档插入books
collection (your ObjectId value will differ):books
集合(您的ObjectId值将不同):
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 例如,以下更新将upsert选项设置为true
:true
:
If no documents match the query condition, the operation inserts the following document (your ObjectId value will differ):如果没有与查询条件匹配的文档,操作将插入以下文档(ObjectId值将不同):
See also参阅
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
操作指定使用
$replaceRoot
stage which can provide somewhat similar behavior to a $setOnInsert
update operator expression,$replaceRoot
阶段可以提供与$setOnInsert
更新运算符表达式类似的行为,$set
stage which can provide similar behavior to the $set
update operator expression,$set
阶段可以提供与$set
更新运算符表达式类似的行为,NOW
, which resolves to the current datetime and can provide similar behavior to the $currentDate
update operator expression.NOW
解析为当前日期时间,可以提供与$currentDate
更新运算符表达式类似的行为。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值将不同):
See also参阅
For additional examples of updates using aggregation pipelines, see Update with Aggregation Pipeline.有关使用聚合管道更新的其他示例,请参阅使用聚合管道更新。
From the 在mongo
shell, insert the following documents into a books
collection:mongo
shell中,将以下文档插入books
集合:
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.如果不存在匹配的文档,该操作将插入新文档。
The operation updates all matching documents and results in the following:该操作会更新所有匹配的文档,并产生以下结果:
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:例如,考虑以下操作:
The operation inserts the following document into the 该操作将以下文档插入books
collection (your ObjectId value will differ):books
集合(您的ObjectId值将不同):
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. 如果试图以这种方式插入文档,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
字段上的条件,因此在构造要插入的文档时,更新将导致错误。
The 操作的WriteResult
of the operation returns the following error:WriteResult
返回以下错误:
See also参阅
Warning
To avoid inserting the same document more than once, only use 为了避免多次插入同一文档,仅当upsert: true
if the query
field is uniquely indexed.query
字段被唯一索引时才使用upsert:true
。
Given a collection named 给定一个名为people
where no documents have a name
field that holds the value Andy
, consider when multiple clients issue the following db.collection.update()
with upsert: true
at the same time:people
的集合,其中没有文档具有值Andy
的name
字段,那么当多个客户端同时发出以下db.collection.update()
配合upsert: true
时:
If all 如果所有db.collection.update()
operations complete the query
portion before any client successfully inserts data, and there is no unique index on the name
field, then each update operation may result in an insert.db.collection.update()
操作在任何客户端成功插入数据之前完成query
部分,并且name
字段上没有唯一的索引,那么每个更新操作都可能导致插入。
To prevent MongoDB from inserting the same document more than once, create a unique index on the 要防止MongoDB多次插入同一文档,请在name
field. name
字段上创建唯一索引。With a unique index, if multiple applications issue the same update with 使用唯一索引,如果多个应用程序使用upsert: true
, exactly one db.collection.update()
would successfully insert a new document.upsert:true
发出相同的更新,则只有一个db.collection.update()
将成功插入新文档。
The remaining operations would either:其余的行动将是:
If the operation fails because of a duplicate index key error, applications may retry the operation which will succeed as an update operation.如果操作因重复索引键错误而失败,应用程序可以重试该操作,该操作将作为更新操作成功。
See also参阅
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
$addFields
及其别名$set
$project
$unset
$replaceRoot
$replaceWith
Using the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).使用聚合管道可以实现更具表现力的update语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。
Create a 使用以下文档创建members
collection with the following documents:members
集合:
Assume that instead of separate 假设不需要单独的misc1
and misc2
fields, you want to gather these into a new comments
field. misc1
和misc2
字段,而是希望将它们收集到一个新的comments
字段中。The following update operation uses an aggregation pipeline to:以下更新操作使用聚合管道来:
comments
field and set the lastUpdate
field.comments
字段并设置lastUpdate
字段。misc1
and misc2
fields for all documents in the collection.misc1
和misc2
字段。Note
The 管道中使用的$set
and $unset
used in the pipeline refers to the aggregation stages $set
and $unset
respectively, and not the update operators $set
and $unset
.$set
和$unset
分别指的是聚合阶段$set
和$unset
,而不是更新运算符$set
和$unset
。
comments
whose elements are the current content of the misc1
and misc2
fields andcomments
,其元素是misc1
和misc2
字段的当前内容,以及lastUpdate
to the value of the aggregation variable NOW
. lastUpdate
设置为聚合变量NOW
的值。NOW
resolves to the current datetime value and remains the same throughout the pipeline. NOW
现在解析为当前日期时间值,并在整个管道中保持不变。$$
and enclose in quotes.$$
并用引号括起来。$unset
stage removes the misc1
and misc2
fields.$unset
阶段删除misc1
和misc2
字段。After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
See also参阅
Create a 使用以下文档创建students3
collection with the following documents:students3
集合:
Using an aggregation pipeline, you can update the documents with the calculated grade average and letter grade.使用聚合管道,可以使用计算出的平均成绩和字母成绩更新文档。
Note
The 管道中使用的$set
used in the pipeline refers to the aggregation stage $set
, and not the update operators $set
.$set
指的是聚合阶段$set
,而不是更新运算符$set
。
average
based on the average of the tests
field. tests
字段的平均值计算新字段average
。$avg
for more information on the $avg
aggregation operator and $trunc
for more information on the $trunc
truncate aggregation operator.$avg
聚合运算符的更多信息,请参阅$avg
;有关$trunc
截断聚合运算符的更多信息,请参见$trunc
。lastUpdate
to the value of the aggregation variable NOW
. lastUpdate
设置为聚合变量NOW
的值。NOW
resolves to the current datetime value and remains the same throughout the pipeline. NOW
现在解析为当前日期时间值,并在整个管道中保持不变。$$
and enclose in quotes.$$
并用引号括起来。$set
stage calculates a new field grade
based on the average
field calculated in the previous stage. $set
阶段根据前一阶段计算的平均字段计算新的字段等级。$switch
for more information on the $switch
aggregation operator.$switch
聚合运算符的更多信息,请参阅$switch
。After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
See also参阅
arrayFilters
for Array Update OperationsarrayFilters
¶In the update document, use the 在更新文档中,使用筛选位置运算符$[<identifier>]
filtered positional operator to define an identifier, which you then reference in the array filter documents. $[<identifier>]
定义一个标识符,然后在数组筛选文档中引用该标识符。You cannot have an array filter document for an identifier if the identifier is not included in the update document.如果标识符未包含在更新文档中,则不能使用标识符的数组筛选器文档。
Note
The <identifier>
must begin with a lowercase letter and contain only alphanumeric characters.<identifier>
必须以小写字母开头,并且只包含字母数字字符。
You can include the same identifier multiple times in the update document; however, for each distinct identifier (您可以在更新文档中多次包含同一标识符;但是,对于更新文档中的每个不同标识符($[identifier]
) in the update document, you must specify exactly one corresponding array filter document. $[identifier]
),必须指定一个对应的数组筛选器文档。That is, you cannot specify multiple array filter documents for the same identifier. 也就是说,不能为同一标识符指定多个数组筛选器文档。For example, if the update statement includes the identifier 例如,如果update语句包含标识符x
(possibly multiple times), you cannot specify the following for arrayFilters
that includes 2 separate filter documents for x
:x
(可能多次),则不能为包含x
的两个单独筛选文档的arrayFilters
指定以下内容:
However, you can specify compound conditions on the same identifier in a single filter document, such as in the following examples:但是,您可以在单个筛选文档中对同一标识符指定复合条件,如以下示例中所示:
arrayFilters
is not available for updates that use an aggregation pipeline.arrayFilters
不适用于使用聚合管道的更新。
arrayFilters
CriteriaarrayFilters
条件¶To update all array elements which match a specified criteria, use the arrayFilters parameter.要更新符合指定条件的所有数组元素,请使用arrayFilters
参数。
From the 从mongo
shell, create a students
collection with the following documents:mongo
shell中,创建一个包含以下文档的students
集合:
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
选项:
After the operation, the collection contains the following documents:操作完成后,集合包含以下文档:
You can also use the arrayFilters parameter to update specific document fields within an array of documents.还可以使用arrayFilters
参数更新文档数组中的特定文档字段。
From the 在mongo
shell, create a students2
collection with the following documents:mongo
shell中,使用以下文档创建students2
集合:
To modify the value of the 要修改等级大于或等于mean
field for all elements in the grades
array where the grade is greater than or equal to 85
, use the filtered positional operator $[<identifier>]
with the arrayFilters
:85
的grades
数组中所有元素的mean
(平均值)字段,请使用筛选位置运算符$[<identifier>]
配合arrayFilters
选项:
After the operation, the collection has the following documents:操作完成后,集合具有以下文档:
hint
for Update Operationshint
¶New in version 4.2.版本4.2中的新功能。
From the 在mongo
shell, create a members
collection with the following documents:mongo
shell中,创建包含以下文档的members
集合:
Create the following indexes on the collection:在集合上创建以下索引:
The following update operation explicitly hints to use the index 以下更新操作明确提示使用索引{status: 1 }
:{status: 1 }
:
Note
If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作将出错。
The update command returns the following:更新命令返回以下内容:
To see the index used, run 要查看使用的索引,请对操作运行explain
on the operation:explain
:
The db.collection.explain().update()
does not modify the documents.db.collection.explain().update()
不会修改文档。
The following operation on a replica set specifies a write concern of 以下对副本集的操作指定了一个写关注点"w: majority"
with a wtimeout
of 5000 milliseconds such that the method returns after the write propagates to a majority of the voting replica set members or the method times out after 5 seconds."w: majority"
,wtimeout
为5000毫秒,这样该方法在写入传播到大多数投票副本集成员后返回,或者该方法在5秒后超时。
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:collaction
选项语法如下所示:
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.例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一种排序规则,对排序使用另一种排序规则。
New in version 3.4.版本3.4中的新功能。
From the 从mongo
shell, create a collection named myColl
with the following documents:mongo
shell创建一个名为myColl
的集合,其中包含以下文档:
The following operation includes the collation option and sets 以下操作包括排序规则选项,并将multi
to true
to update all matching documents:multi
设置为true
以更新所有匹配的文档:
The write result of the operation returns the following document, indicating that all three documents in the collection were updated:操作的写入结果返回以下文档,表明集合中的所有三个文档都已更新:
After the operation, the collection contains the following documents:操作完成后,集合包含以下文档:
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
对象包含符合查询条件的文档数、更新插入的文档数和修改的文档数:
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.4.在版本4.4中更改。
The following table explains the possible values of 下表说明了WriteResult.writeConcernError.provenance
:WriteResult.writeConcernError.provenance
的可能值:
Provenance | |
---|---|
clientSupplied |
|
customDefault |
setDefaultRWConcern .setDefaultRWConcern 。 |
getLastErrorDefaults |
settings.getLastErrorDefaults field.settings.getLastErrorDefaults 字段。 |
implicitDefault |
See also参阅