db.collection.updateMany()

Definition

  • db.collection.updateMany(filter, update, options)

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

New in version 3.2.

Updates all documents that match the specified filter for acollection.

Syntax

The updateMany() method has the following form:

  1. db.collection.updateMany(
  2. <filter>,
  3. <update>,
  4. {
  5. upsert: <boolean>,
  6. writeConcern: <document>,
  7. collation: <document>,
  8. arrayFilters: [ <filterdocument1>, ... ],
  9. hint: <document|string> // Available starting in MongoDB 4.2.1
  10. }
  11. )

Parameters

The updateMany() method takes the followingparameters:

ParameterTypeDescription
filterdocumentThe selection criteria for the update. The same queryselectors as in the find() method are available.Specify an empty document { } to update all documents inthe collection.
updatedocumentThe modifications to apply.The value can be either:- A document that contains update operator expressions, or- Starting in MongoDB 4.2, an aggregation pipeline. The pipeline canconsist of the following stages: - $addFields and its alias $set - $project and its alias $unset - $replaceRoot and its alias $replaceWith.For more information on the update modification parameter, seeUpdate with an Update Operator Expressions Document andUpdate with an Aggregation Pipeline.To update with a replacement document, seedb.collection.replaceOne().
upsertbooleanOptional. When true, updateMany() either:- Creates a new document if no documents match the filter.For more details see upsert behavior.- Updates documents that match the filter.To avoid multiple upserts, ensure that the filter fieldsare uniquely indexed.Defaults to false.
writeConcerndocumentOptional. A document expressing the write concern. Omit to use the default write concern.Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.
collationdocumentOptional.Specifies the collation to use for the operation.Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.The collation option has the following syntax:
  1. 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; allother collation fields are optional. For descriptions of the fields,see Collation Document.If the collation is unspecified but the collection has adefault collation (see db.createCollection()), theoperation uses the collation specified for the collection.If no collation is specified for the collection or for theoperations, MongoDB uses the simple binary comparison used in priorversions for string comparisons.You cannot specify multiple collations for an operation. Forexample, you cannot specify different collations per field, or ifperforming a find with a sort, you cannot use one collation for thefind and another for the sort.New in version 3.4.
arrayFiltersarrayOptional. An array of filter documents that determine which array elements tomodify for an update operation on an array field.In the update document, use the $[<identifier>] filteredpositional operator to define an identifier, which you then referencein the array filter documents. You cannot have an array filterdocument for an identifier if the identifier is not included in theupdate document.NoteThe <identifier> must begin with a lowercase letter andcontain only alphanumeric characters.You can include the same identifier multiple times in the updatedocument; however, for each distinct identifier ($[identifier])in the update document, you must specify exactly onecorresponding array filter document. That is, you cannot specifymultiple array filter documents for the same identifier. Forexample, if the update statement includes the identifier x(possibly multiple times), you cannot specify the following forarrayFilters that includes 2 separate filter documents for x:
  1. // INVALID[ { "x.a": { $gt: 85 } }, { "x.b": { $gt: 80 } }]
However, you can specify compound conditions on the same identifierin a single filter document, such as in the following examples:
  1. // Example 1[ { $or: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }]// Example 2[ { $and: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }]// Example 3[ { "x.a": { $gt: 85 }, "x.b": { $gt: 80 } }]
For examples, see Specify arrayFilters for an Array Update Operations.New in version 3.6.
hintDocument or stringOptional. A document or string that specifies the index to use to support the query predicate.The option can take an index specification document or the indexname string.If you specify an index that does not exist, the operationerrors.For an example, see Specify hint for Update Operations.New in version 4.2.1.

Returns

The method returns a document that contains:

  • A boolean acknowledged as true if the operation ran withwrite concern or false if write concern was disabled
  • matchedCount containing the number of matched documents
  • modifiedCount containing the number of modified documents
  • upsertedId containing the _id for the upserted document

Access Control

On deployments running with authorization, theuser must have access that includes the following privileges:

  • update action on the specified collection(s).
  • find action on the specified collection(s).
  • insert action on the specified collection(s) if theoperation results in an upsert.

The built-in role readWrite provides the requiredprivileges.

Behavior

updateMany() updates all matching documents inthe collection that match the filter, using the update criteriato apply modifications.

Upsert

If upsert: true and no documents match the filter,db.collection.updateMany() creates a newdocument based on the filter and update parameters.

If you specify upsert: true on a sharded collection, you mustinclude the full shard key in the filter. For additionaldb.collection.updateMany() behavior, seeSharded Collections.

SeeUpdate Multiple Documents with Upsert.

Update with an Update Operator Expressions Document

For the modification specification, thedb.collection.updateMany() method can accept a document thatonly contains update operator expressions toperform.

For example:

  1. db.collection.updateMany(
  2. <query>,
  3. { $set: { status: "D" }, $inc: { quantity: 2 } },
  4. ...
  5. )

Update with an Aggregation Pipeline

Starting in MongoDB 4.2, the db.collection.updateMany() methodcan accept an aggregation pipeline [ <stage1>, <stage2>, … ] thatspecifies the modifications to perform. The pipeline can consist ofthe following stages:

Using the aggregation pipeline allows for a more expressive updatestatement, such as expressing conditional updates based on currentfield values or updating one field using the value of another field(s).

For example:

  1. db.collection.updateMany(
  2. <query>,
  3. [
  4. { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
  5. { $unset: [ "misc1", "misc2" ] }
  6. ]
  7. ...
  8. )

Note

The $set and $unset used in the pipeline refers to theaggregation stages $set and $unsetrespectively, and not the update operators $set and $unset.

For examples, see Update with Aggregation Pipeline.

Capped Collections

If an update operation changes the document size, the operation will fail.

Sharded Collections

For a db.collection.updateMany() operation that includesupsert: true and is on a sharded collection, you must include thefull shard key in the filter.

Explainability

updateMany() is not compatible withdb.collection.explain().

Use update() instead.

Transactions

db.collection.updateMany() can be used inside multi-document transactions.

If the operation results in an upsert, the collection must already exist.

Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

Examples

Update Multiple Documents

The restaurant collection contains the following documents:

  1. { "_id" : 1, "name" : "Central Perk Cafe", "violations" : 3 }
  2. { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "violations" : 2 }
  3. { "_id" : 3, "name" : "Empire State Sub", "violations" : 5 }
  4. { "_id" : 4, "name" : "Pizza Rat's Pizzaria", "violations" : 8 }

The following operation updates all documents where violations aregreater than 4 and $set a flag for review:

  1. try {
  2. db.restaurant.updateMany(
  3. { violations: { $gt: 4 } },
  4. { $set: { "Review" : true } }
  5. );
  6. } catch (e) {
  7. print(e);
  8. }

The operation returns:

  1. { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

The collection now contains the following documents:

  1. { "_id" : 1, "name" : "Central Perk Cafe", "violations" : 3 }
  2. { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "violations" : 2 }
  3. { "_id" : 3, "name" : "Empire State Sub", "violations" : 5, "Review" : true }
  4. { "_id" : 4, "name" : "Pizza Rat's Pizzaria", "violations" : 8, "Review" : true }

If no matches were found, the operation instead returns:

  1. { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }

Setting upsert: true would insert a document if no match was found.

Update with Aggregation Pipeline

Starting in MongoDB 4.2, the db.collection.updateMany() can usean aggregation pipeline for the update. The pipeline can consist of thefollowing stages:

Using the aggregation pipeline allows for a more expressive updatestatement, such as expressing conditional updates based on currentfield values or updating one field using the value of another field(s).

Example 1

The following examples uses the aggregation pipeline to modify a fieldusing the values of the other fields in the document.

Create a members collection with the following documents:

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

Assume that instead of separate misc1 and misc2 fields, youwant to gather these into a new comments field. The followingupdate operation uses an aggregation pipeline to add the newcomments field and remove the misc1 and misc2 fields forall documents in the collection.

  1. db.members.updateMany(
  2. { },
  3. [
  4. { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
  5. { $unset: [ "misc1", "misc2" ] }
  6. ]
  7. )

Note

The $set and $unset used in the pipeline refers to theaggregation stages $set and $unsetrespectively, and not the update operators $set and $unset.

  • First Stage
  • The $set stage creates a new array field commentswhose elements are the current content of the misc1 andmisc2 fields.
  • Second Stage
  • The $unset stage removes the misc1 and misc2 fields.

After the command, the collection contains the following documents:

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

Example 2

The aggregation pipeline allows the update to perform conditionalupdates based on the current field values as well as use current fieldvalues to calculate a separate field value.

For example, create a students3 collection with the following documents:

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

Using an aggregation pipeline, you can update the documents with thecalculated grade average and letter grade.

  1. db.students3.updateMany(
  2. { },
  3. [
  4. { $set: { average : { $avg: "$tests" } } },
  5. { $set: { grade: { $switch: {
  6. branches: [
  7. { case: { $gte: [ "$average", 90 ] }, then: "A" },
  8. { case: { $gte: [ "$average", 80 ] }, then: "B" },
  9. { case: { $gte: [ "$average", 70 ] }, then: "C" },
  10. { case: { $gte: [ "$average", 60 ] }, then: "D" }
  11. ],
  12. default: "F"
  13. } } } }
  14. ]
  15. )

Note

The $set used in the pipeline refers to the aggregation stage$set, and not the update operators $set.

  • First Stage
  • The $set stage calculates a new field average basedon the average of the tests field. See $avg formore information on the $avg aggregation operator.
  • Second Stage
  • The $set stage calculates a new field grade based onthe average field calculated in the previous stage. See$switch for more information on the $switchaggregation operator.

After the command, the collection contains the following documents:

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

Update Multiple Documents with Upsert

The inspectors collection contains the following documents:

  1. { "_id" : 92412, "inspector" : "F. Drebin", "Sector" : 1, "Patrolling" : true },
  2. { "_id" : 92413, "inspector" : "J. Clouseau", "Sector" : 2, "Patrolling" : false },
  3. { "_id" : 92414, "inspector" : "J. Clouseau", "Sector" : 3, "Patrolling" : true },
  4. { "_id" : 92415, "inspector" : "R. Coltrane", "Sector" : 3, "Patrolling" : false }

The following operation updates all documents with Sector greaterthan 4 and inspector equal to "R. Coltrane":

  1. try {
  2. db.inspectors.updateMany(
  3. { "Sector" : { $gt : 4 }, "inspector" : "R. Coltrane" },
  4. { $set: { "Patrolling" : false } },
  5. { upsert: true }
  6. );
  7. } catch (e) {
  8. print(e);
  9. }

The operation returns:

  1. {
  2. "acknowledged" : true,
  3. "matchedCount" : 0,
  4. "modifiedCount" : 0,
  5. "upsertedId" : ObjectId("56fc5dcb39ee682bdc609b02")
  6. }

The collection now contains the following documents:

  1. { "_id" : 92412, "inspector" : "F. Drebin", "Sector" : 1, "Patrolling" : true },
  2. { "_id" : 92413, "inspector" : "J. Clouseau", "Sector" : 2, "Patrolling" : false },
  3. { "_id" : 92414, "inspector" : "J. Clouseau", "Sector" : 3, "Patrolling" : true },
  4. { "_id" : 92415, "inspector" : "R. Coltrane", "Sector" : 3, "Patrolling" : false },
  5. { "_id" : ObjectId("56fc5dcb39ee682bdc609b02"), "inspector" : "R. Coltrane", "Patrolling" : false }

Since no documents matched the filter, and upsert was true,updateMany inserted the document with agenerated _id, the equality conditions from the filter, and theupdate modifiers.

Update with Write Concern

Given a three member replica set, the following operation specifies aw of majority and wtimeout of 100:

  1. try {
  2. db.restaurant.updateMany(
  3. { "name" : "Pizza Rat's Pizzaria" },
  4. { $inc: { "violations" : 3}, $set: { "Closed" : true } },
  5. { w: "majority", wtimeout: 100 }
  6. );
  7. } catch (e) {
  8. print(e);
  9. }

If the acknowledgement takes longer than the wtimeout limit, the followingexception is thrown:

  1. WriteConcernError({
  2. "code" : 64,
  3. "errInfo" : {
  4. "wtimeout" : true
  5. },
  6. "errmsg" : "waiting for replication timed out"
  7. }) :
  8. undefined

The wtimeout error only indicates that the operation did not complete ontime. The write operation itself can still succeed outside of the set timelimit.

Specify Collation

New in version 3.4.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

A collection myColl has the following documents:

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

The following operation includes the collationoption:

  1. db.myColl.updateMany(
  2. { category: "cafe" },
  3. { $set: { status: "Updated" } },
  4. { collation: { locale: "fr", strength: 1 } }
  5. );

Specify arrayFilters for an Array Update Operations

New in version 3.6.

Starting in MongoDB 3.6, when updating an array field, you canspecify arrayFilters that determine which array elements toupdate.

Update Elements Match arrayFilters Criteria

Create a collection students with the following documents:

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

To update all elements that are greater than or equal to 100 in thegrades array, use the filtered positional operator$[<identifier>] with the arrayFilters option:

  1. db.students.updateMany(
  2. { grades: { $gte: 100 } },
  3. { $set: { "grades.$[element]" : 100 } },
  4. { arrayFilters: [ { "element": { $gte: 100 } } ] }
  5. )

After the operation, the collection contains the following documents:

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

Update Specific Elements of an Array of Documents

Create a collection students2 with the following documents:

  1. db.students2.insert([
  2. {
  3. "_id" : 1,
  4. "grades" : [
  5. { "grade" : 80, "mean" : 75, "std" : 6 },
  6. { "grade" : 85, "mean" : 90, "std" : 4 },
  7. { "grade" : 85, "mean" : 85, "std" : 6 }
  8. ]
  9. },
  10. {
  11. "_id" : 2,
  12. "grades" : [
  13. { "grade" : 90, "mean" : 75, "std" : 6 },
  14. { "grade" : 87, "mean" : 90, "std" : 3 },
  15. { "grade" : 85, "mean" : 85, "std" : 4 }
  16. ]
  17. }
  18. ])

To modify the value of the mean field for all elements in thegrades array where the grade is greater than or equal to 85,use the filtered positional operator $[<identifier>] withthe arrayFilters:

  1. db.students2.updateMany(
  2. { },
  3. { $set: { "grades.$[elem].mean" : 100 } },
  4. { arrayFilters: [ { "elem.grade": { $gte: 85 } } ] }
  5. )

After the operation, the collection has the following documents:

  1. {
  2. "_id" : 1,
  3. "grades" : [
  4. { "grade" : 80, "mean" : 75, "std" : 6 },
  5. { "grade" : 85, "mean" : 100, "std" : 4 },
  6. { "grade" : 85, "mean" : 100, "std" : 6 }
  7. ]
  8. }
  9. {
  10. "_id" : 2,
  11. "grades" : [
  12. { "grade" : 90, "mean" : 100, "std" : 6 },
  13. { "grade" : 87, "mean" : 100, "std" : 3 },
  14. { "grade" : 85, "mean" : 100, "std" : 4 }
  15. ]
  16. }

Specify hint for Update Operations

New in version 4.2.1.

Create a sample members collection with the following documents:

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

Create the following indexes on the collection:

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

The following update operation explicitly hints to use the index {status: 1 }:

Note

If you specify an index that does not exist, the operation errors.

  1. db.members.updateMany(
  2. { "points": { $lte: 20 }, "status": "P" },
  3. { $set: { "misc1": "Need to activate" } },
  4. { hint: { status: 1 } }
  5. )

The update command returns the following:

  1. { "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

To view the indexes used, you can use the $indexStats pipeline:

  1. db.members.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] )