On this page本页内容
db.collection.updateMany(filter, 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驱动程序文档。
New in version 3.2.版本3.2中的新功能。
Updates all documents that match the specified filter for a collection.更新与集合的指定筛选器匹配的所有文档。
The updateMany() method has the following form:updateMany()方法的形式如下:
The updateMany() method takes the following parameters:updateMany()方法采用以下参数:
| filter | document |
| ||||
| update | document or pipeline |
| ||||
upsert |
boolean |
| ||||
writeConcern |
document |
| ||||
collation |
document |
The collation option
| ||||
arrayFilters |
array |
Note
| ||||
| hint | Document or string |
New in version 4.2.1. |
The method returns a document that contains:该方法返回一个包含以下内容的文档:
acknowledged as true if the operation ran with write concern or false if write concern was disabledacknowledged为true;如果写关注点被禁用,则布尔值acknowledged为falsematchedCountmodifiedCountupsertedId_id for the upserted document_idOn 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.insert操作。The built-in role 内置角色readWrite provides the required privileges.readWrite提供所需的权限。
updateMany() updates all matching documents in the collection that match the 使用filter, using the update criteria to apply modifications.update条件应用修改,更新集合中与filter匹配的所有匹配文档。
If 如果upsert: true and no documents match the filter, db.collection.updateMany() creates a new document based on the filter and update parameters.upsert:true且没有与filter匹配的文档,db.collection.updateMany()将基于筛选器和更新参数创建一个新文档。
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.updateMany() behavior, see Sharded Collections.db.collection.updateMany()行为,请参阅碎片集合。
See Update Multiple Documents with Upsert.请参见使用Upsert更新多个文档。
For the modification specification, the 对于修改规范,db.collection.updateMany() method can accept a document that only contains update operator expressions to perform.db.collection.updateMany()方法可以接受只包含要执行的更新运算符表达式的文档。
For example:例如:
Starting in MongoDB 4.2, the 从MongoDB 4.2开始,db.collection.updateMany() method can accept an aggregation pipeline [ <stage1>, <stage2>, ... ] that specifies the modifications to perform. db.collection.updateMany()方法可以接受聚合管道[ <stage1>, <stage2>, ... ]指定要执行的修改。The pipeline can consist of the following stages:管道可包括以下阶段:
$addFields$set$project$unset$replaceRoot$replaceWithUsing the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).使用聚合管道可以实现更具表现力的update语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。
For example:例如:
Note
The $set and $unset used in the pipeline refers to the aggregation stages $set and $unset respectively, and not the update operators $set and $unset.
For examples, see Update with Aggregation Pipeline.有关示例,请参阅使用聚合管道更新。
If an update operation changes the document size, the operation will fail.如果更新操作更改了文档大小,则操作将失败。
For a 对于包含db.collection.updateMany() 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.updateMany()操作,必须在筛选器中包含完整的分片密钥。
updateMany() is not compatible with 与db.collection.explain().不兼容。
db.collection.updateMany() can be used inside multi-document transactions.可以在多文档事务中使用。
Important
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,而多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
Starting in MongoDB 4.4 with feature compatibility version (fcv) 从功能兼容版本(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.updateMany() with upsert: true can be run against an existing collection or a non-existing collection. "4.4"或更高版本的情况,可以对现有集合或不存在的集合运行带有upsert:true的db.collection.updateMany()。If run against a non-existing collection, the operation creates the collection.如果针对不存在的集合运行,该操作将创建该集合。
If the feature compatibility version (fcv) is 如果功能兼容版本(fcv)为"4.2" or less, the operation must be against an existing collection."4.2"或更低,则操作必须针对现有集合。
Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注点。To use write concern with transactions, see Transactions and Write Concern.要将写关注点用于事务,请参阅事务和写关注点。
The restaurant collection contains the following documents:restaurant集合包含以下文档:
The following operation updates all documents where 以下操作将更新violations are greater than 4 and $set a flag for review:violations行为大于4的所有文档,并$set标记以供审核:
The operation returns:操作返回:
The collection now contains the following documents:该集合现在包含以下文档:
If no matches were found, the operation instead returns:如果未找到匹配项,则操作将返回:
Setting 设置upsert: true would insert a document if no match was found.upsert:true将在未找到匹配项时插入文档。
Starting in MongoDB 4.2, the 从MongoDB 4.2开始,db.collection.updateMany() can use an aggregation pipeline for the update. db.collection.updateMany()可以使用聚合管道进行更新。The pipeline can consist of the following stages:管道可包括以下阶段:
$addFields and its alias $set$project and its alias $unset$replaceRoot and its alias $replaceWith.Using the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).使用聚合管道可以实现更具表现力的update语句,例如基于当前字段值表达条件更新,或者使用另一个字段的值更新一个字段。
The following examples uses the aggregation pipeline to modify a field using the values of the other fields in the document.以下示例使用聚合管道使用文档中其他字段的值修改字段。
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。
The $set stage:
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.After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
The aggregation pipeline allows the update to perform conditional updates based on the current field values as well as use current field values to calculate a separate field value.聚合管道允许更新基于当前字段值执行条件更新,并使用当前字段值计算单独的字段值。
For example, 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阶段根据前一阶段计算的average字段计算新的字段grade。$switch for more information on the $switch aggregation operator.$switch聚合运算符的更多信息,请参阅$switch。After the command, the collection contains the following documents:命令发出后,集合包含以下文档:
See also参阅
The inspectors collection contains the following documents:inspectors集合包含以下文档:
The following operation updates all documents with 以下操作将更新Sector greater than 4 and inspector equal to "R. Coltrane":Sector大于4且inspector等于"R. Coltrane"的所有文档:
The operation returns:操作返回:
The collection now contains the following documents:该集合现在包含以下文档:
Since no documents matched the filter, and 由于没有与筛选器匹配的文档,且upsert was true, updateMany inserted the document with a generated _id, the equality conditions from the filter, and the update modifiers.upsert为true,updateMany可以使用生成的_id、filter中的相等条件和update修饰符插入文档。
Given a three member replica set, the following operation specifies a 给定一个由三个成员组成的副本集,以下操作指定w of majority and wtimeout of 100:w:majority、w:100:
If the acknowledgement takes longer than the 如果确认时间超过wtimeout limit, the following exception is thrown:wtimeout限制,则会引发以下异常:
Changed in version 4.4.在版本4.4中更改。
The following table explains the possible values of 下表说明了errInfo.writeConcern.provenance:errInfo.writeConcern.provenance的可能值:
clientSupplied |
|
customDefault |
setDefaultRWConcern.setDefaultRWConcern。 |
getLastErrorDefaults |
settings.getLastErrorDefaults field.settings.getLastErrorDefaults字段。 |
implicitDefault |
New in version 3.4.版本3.4中的新功能。
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。
A collection myColl has the following documents:myColl集合包含以下文档:
The following operation includes the collation option:以下操作包括排序规则选项:
arrayFilters for an Array Update OperationsarrayFilters ¶New in version 3.6.版本3.6中的新功能。
Starting in MongoDB 3.6, when updating an array field, you can specify 从MongoDB 3.6开始,在更新数组字段时,可以指定确定要更新哪些数组元素的arrayFilters that determine which array elements to update.arrayFilters。
arrayFilters CriteriaarrayFilters条件¶Create a collection 创建一个包含以下文档的students with the following documents:students集合:
To 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>]:
After the operation, the collection contains the following documents:操作完成后,集合包含以下文档:
Create a collection 使用以下文档创建students2 with the following documents:students2集合:
To modify the value of the 要修改等级大于或等于mean field for all elements in the grades array where the grade is greater than or equal to 85, use the filtered positional operator $[<identifier>] with the arrayFilters:85的grades数组中所有元素的mean字段,请使用筛选后的位置运算符$[<identifier>]和arrayFilters:
After the operation, the collection has the following documents:操作完成后,集合具有以下文档:
hint for Update Operationshint¶New in version 4.2.1.在4.2.1版中新增。
Create a sample 使用以下文档创建示例members collection with the following documents:members集合:
Create the following indexes on the collection:在集合上创建以下索引:
The following update operation explicitly hints to use the index 以下更新操作明确提示使用索引{ status: 1 }:{status: 1}:
Note
If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作将出错。
The update command returns the following:更新命令返回以下内容:
To view the indexes used, you can use the 要查看使用的索引,可以使用$indexStats pipeline:$indexStats管道: