db.collection.update()

Definition

  • db.collection.update(query, 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.

Modifies an existing document or documents in a collection. Themethod can modify specific fields of an existing document or documentsor replace an existing document entirely, depending on theupdate parameter.

By default, the db.collection.update() method updates asingle document. Include the option multi: trueto update all documents that match the query criteria.

Syntax

The db.collection.update() method has the following form:

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

Parameters

The db.collection.update() method takes the followingparameters:

ParameterTypeDescription
querydocumentThe selection criteria for the update. The same queryselectors as in the find() method are available.Changed in version 3.0: When you execute an update() with upsert:true and the query matches no existing document, MongoDB will refuseto insert a new document if the query specifies conditions on the_id field using dot notation.
updatedocument or pipelineThe modifications to apply. Can be one of the following:
Update documentContains only update operator expressions.
Replacement documentContains only <field1>: <value1> pairs.
Aggregation pipelineConsists only of the following aggregation stages:- $addFields and its alias $set- $project and its alias $unset- $replaceRoot and its alias $replaceWith.

For details and examples, see Examples.

upsertbooleanOptional. If set to true, creates a new document when nodocument matches the query criteria. The default value isfalse, which does not insert a new document when no matchis found.
multibooleanOptional. If set to true, updates multiple documents thatmeet the query criteria. If set to false, updates onedocument. The default value is false. For additionalinformation, see Update Multiple Documents Examples.
writeConcerndocumentOptional. A document expressing the write concern. Omit to use the default writeconcern w: 1.

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

For an example using writeConcern, seeOverride Default Write Concern.

collationdocumentOptional.

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

For an example using collation, seeSpecify Collation.

New in version 3.4.

arrayFiltersarrayOptional. An array of filter documents that determine which arrayelements to modify for an update operation on an array field.

In the update document, use the$[<identifier>] to define an identifier to updateonly those array elements that match the corresponding filterdocument in the arrayFilters.

Note

You cannot have an array filter document for an identifier ifthe identifier is not included in the update document.

For examples, see Specify arrayFilters for 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.

Returns

The method returns a WriteResult document that containsthe status of the operation.

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

Sharded Collections

To use db.collection.update() with multi: false on asharded collection, you must include an exact match on the _idfield or target a single shard (such as by including the shard key).

When the db.collection.update() performs update operations(and not document replacement operations),db.collection.update() can target multiple shards.

See also

findAndModify()

Replace Document Operations on a Sharded Collection

Starting in MongoDB 4.2, replace document operations attempt to targeta single shard, first by using the query filter. If the operationcannot target a single shard by the query filter, it then attempts to targetby the replacement document.

In earlier versions, the operation attempts to target using thereplacement document.

upsert on a Sharded Collection

For a db.collection.update() operation that includesupsert: true and is on a sharded collection, youmust include the full shard key in the filter:

  • For an update operation.
  • For a replace document operation (starting in MongoDB 4.2).

Shard Key Modification

Starting in MongoDB 4.2, you can update a document’s shard key valueunless the shard key field is the immutable _id field. For detailson updating the shard key, see Change a Document’s Shard Key Value.

Before MongoDB 4.2, a document’s shard key field value is immutable.

To use db.collection.update() to update the shard key:

  • You must specify multi: false.
  • You must run on a mongos either in atransaction or as a retryablewrite. Do not issue the operationdirectly on the shard.
  • You must include an equality condition on the full shardkey in the query filter. For example, if a collection messagesuses { country : 1, userid : 1 } as the shard key, to updatethe shard key for a document, you must include country: <value>,userid: <value> in the query filter. You can include additionalfields in the query as appropriate.

Transactions

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

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.

Existing Collections and Transactions

Inside a transaction, you can specify read/write operations on existingcollections. If the db.collection.update() results in anupsert, the collection must already exist.

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

Write Concerns and Transactions

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

Examples

  • Use Update Operator Expressions ($inc, $set)
  • Push Elements to Existing Array
  • Remove Fields ($unset)
  • Replace Entire Document
  • Update Multiple Documents

From the mongo shell, create a books collection whichcontains the following documents. This command first removes allpreviously existing documents from the books collection:

  1. db.books.remove({});
  2.  
  3. db.books.insertMany([
  4. {
  5. "_id" : 1,
  6. "item" : "TBD",
  7. "stock" : 0,
  8. "info" : { "publisher" : "1111", "pages" : 430 },
  9. "tags" : [ "technology", "computer" ],
  10. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
  11. "reorder" : false
  12. },
  13. {
  14. "_id" : 2,
  15. "item" : "XYZ123",
  16. "stock" : 15,
  17. "info" : { "publisher" : "5555", "pages" : 150 },
  18. "tags" : [ ],
  19. "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
  20. "reorder" : false
  21. }
  22. ]);

If the <update> document contains update operator modifiers, such as those using the$set modifier, then:

  • The <update> document must contain onlyupdate operator expressions.
  • The db.collection.update() method updates only thecorresponding fields in the document.
    • 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 inan array, use dot notationto specify the field.

You can use the web shell below to insert the sampledocuments and execute the example update operation:

  1. db.books.update(
  2. { _id: 1 },
  3. {
  4. $inc: { stock: 5 },
  5. $set: {
  6. item: "ABC123",
  7. "info.publisher": "2222",
  8. tags: [ "software" ],
  9. "ratings.1": { by: "xyz", rating: 3 }
  10. }
  11. }
  12. )

In this operation:

  • The <query> parameter of { _id: 1 } specifies whichdocument to update,
  • the $inc operator increments the stock field,and
  • the $set operator replaces the value of the
    • item field,
    • publisher field in the info embedded document,
    • tags field, and
    • second element in the ratings array.

The updated document is the following:

  1. {
  2. "_id" : 1,
  3. "item" : "ABC123",
  4. "stock" : 5,
  5. "info" : { "publisher" : "2222", "pages" : 430 },
  6. "tags" : [ "software" ],
  7. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
  8. "reorder" : false
  9. }

This operation corresponds to the following SQL statement:

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

Note

If the query parameter had matched multiple documents,this operation would only update one matching document. Toupdate multiple documents, you must set the multi optionto true.

See also

$set, $inc,Update Operators,dot notation

From the mongo shell, create a books collection whichcontains the following documents. This command first removes allpreviously existing documents from the books collection:

  1. db.books.remove({});
  2.  
  3. db.books.insertMany([
  4. {
  5. "_id" : 1,
  6. "item" : "TBD",
  7. "stock" : 0,
  8. "info" : { "publisher" : "1111", "pages" : 430 },
  9. "tags" : [ "technology", "computer" ],
  10. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
  11. "reorder" : false
  12. },
  13. {
  14. "_id" : 2,
  15. "item" : "XYZ123",
  16. "stock" : 15,
  17. "info" : { "publisher" : "5555", "pages" : 150 },
  18. "tags" : [ ],
  19. "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
  20. "reorder" : false
  21. }
  22. ]);

The following operation uses the $push updateoperator to append a new object to the ratings array.

You can use the web shell below to insert the sampledocuments and execute the example update operation:

  1. db.books.update(
  2. { _id: 2 },
  3. {
  4. $push: { ratings: { "by" : "jkl", "rating" : 2 } }
  5. }
  6. )

The updated document is the following:

  1. {
  2. "_id" : 2,
  3. "item" : "XYZ123",
  4. "stock" : 15,
  5. "info" : {
  6. "publisher" : "5555",
  7. "pages" : 150
  8. },
  9. "tags" : [ ],
  10. "ratings" : [
  11. { "by" : "xyz", "rating" : 5 },
  12. { "by" : "jkl", "rating" : 2 }
  13. ],
  14. "reorder" : false
  15. }

See also

$push

From the mongo shell, create a books collection whichcontains the following documents. This command first removes allpreviously existing documents from the books collection:

  1. db.books.remove({});
  2.  
  3. db.books.insertMany([
  4. {
  5. "_id" : 1,
  6. "item" : "TBD",
  7. "stock" : 0,
  8. "info" : { "publisher" : "1111", "pages" : 430 },
  9. "tags" : [ "technology", "computer" ],
  10. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
  11. "reorder" : false
  12. },
  13. {
  14. "_id" : 2,
  15. "item" : "XYZ123",
  16. "stock" : 15,
  17. "info" : { "publisher" : "5555", "pages" : 150 },
  18. "tags" : [ ],
  19. "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
  20. "reorder" : false
  21. }
  22. ]);

The following operation uses the $unset operator to removethe tags field from the document with { _id: 1 }.

You can use the web shell below to insert the sampledocuments and execute the example update operation:

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

The updated document is the following:

  1. {
  2. "_id" : 1,
  3. "item" : "TBD",
  4. "stock" : 0,
  5. "info" : {
  6. "publisher" : "1111",
  7. "pages" : 430
  8. },
  9. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
  10. "reorder" : false
  11. }

There is not a direct SQL equivalent to $unset,however $unset is similar to the following SQLcommand which removes the tags field from the bookstable:

  1. ALTER TABLE books
  2. DROP COLUMN tags

See also

$unset, $rename, Update Operators

From the mongo shell, create a books collection whichcontains the following documents. This command first removes allpreviously existing documents from the books collection:

  1. db.books.remove({});
  2.  
  3. db.books.insertMany([
  4. {
  5. "_id" : 1,
  6. "item" : "TBD",
  7. "stock" : 0,
  8. "info" : { "publisher" : "1111", "pages" : 430 },
  9. "tags" : [ "technology", "computer" ],
  10. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
  11. "reorder" : false
  12. },
  13. {
  14. "_id" : 2,
  15. "item" : "XYZ123",
  16. "stock" : 15,
  17. "info" : { "publisher" : "5555", "pages" : 150 },
  18. "tags" : [ ],
  19. "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
  20. "reorder" : false
  21. }
  22. ]);

If the <update> document contains only field:valueexpressions, then:

The following operation passes an <update> document that containsonly field and value pairs. The <update> document completelyreplaces the original document except for the _id field.

You can use the web shell below to insert the sampledocuments and execute the example update operation:

  1. db.books.update(
  2. { _id: 2 },
  3. {
  4. item: "XYZ123",
  5. stock: 10,
  6. info: { publisher: "2255", pages: 150 },
  7. tags: [ "baking", "cooking" ]
  8. }
  9. )

The updated document contains only the fields from thereplacement document and the _id field. As such, the fieldsratings and reorder no longer exist in the updateddocument since the fields were not in the replacement document.

  1. {
  2. "_id" : 2,
  3. "item" : "XYZ123",
  4. "stock" : 10,
  5. "info" : { "publisher" : "2255", "pages" : 150 },
  6. "tags" : [ "baking", "cooking" ]
  7. }

This operation corresponds to the following SQL statements:

  1. DELETE from books WHERE _id = 2
  2.  
  3. INSERT INTO books
  4. (_id,
  5. item,
  6. stock,
  7. publisher,
  8. pages,
  9. tags)
  10. VALUES (2,
  11. "xyz123",
  12. 10,
  13. "2255",
  14. 150,
  15. "baking,cooking")

From the mongo shell, create a books collection whichcontains the following documents. This command first removes allpreviously existing documents from the books collection:

  1. db.books.remove({});
  2.  
  3. db.books.insertMany([
  4. {
  5. "_id" : 1,
  6. "item" : "TBD",
  7. "stock" : 0,
  8. "info" : { "publisher" : "1111", "pages" : 430 },
  9. "tags" : [ "technology", "computer" ],
  10. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
  11. "reorder" : false
  12. },
  13. {
  14. "_id" : 2,
  15. "item" : "XYZ123",
  16. "stock" : 15,
  17. "info" : { "publisher" : "5555", "pages" : 150 },
  18. "tags" : [ ],
  19. "ratings" : [ { "by" : "xyz", "rating" : 5 } ],
  20. "reorder" : false
  21. }
  22. ]);

If multi is set to true, thedb.collection.update() method updates all documentsthat meet the <query> criteria. The multi updateoperation may interleave with other read/write operations.

The following operation sets the reorder field to truefor all documents where stock is less than or equal to10. If the reorder field does not exist in the matchingdocument(s), the $set operator adds the fieldwith the specified value.

You can use the web shell below to insert the sampledocuments and execute the example update operation:

  1. db.books.update(
  2. { stock: { $lte: 10 } },
  3. { $set: { reorder: true } },
  4. { multi: true }
  5. )

The resulting documents in the collection are the following:

  1. [
  2. {
  3. "_id" : 1,
  4. "item" : "ABC123",
  5. "stock" : 5,
  6. "info" : {
  7. "publisher" : "2222",
  8. "pages" : 430
  9. },
  10. "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
  11. "reorder" : true
  12. }
  13. {
  14. "_id" : 2,
  15. "item" : "XYZ123",
  16. "stock" : 10,
  17. "info" : { "publisher" : "2255", "pages" : 150 },
  18. "tags" : [ "baking", "cooking" ],
  19. "reorder" : true
  20. }
  21. ]

This operation corresponds to the following SQL statement:

  1. UPDATE books
  2. SET reorder=true
  3. WHERE stock <= 10

Note

You cannot specify multi: true when performing areplacement, i.e., when the <update> document contains onlyfield:value expressions.

See also

$set

Insert a New Document if No Match Exists (Upsert)

When you specify the option upsert: true:

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

  • Upsert with Replacement Document
  • Upsert with Operator Expressions
  • Aggregation Pipeline using Upsert
  • Combine Upsert and Multi Options
  • Upsert with Dotted _id Query

If no document matches the query criteria and the <update>parameter is a replacement document (i.e., contains only fieldand value pairs), the update inserts a new document with thefields and values of the replacement document.

  • If you specify an _id field in either the query parameteror replacement document, MongoDB uses that _id field in theinserted document.

  • If you do not specify an _id field in either the queryparameter or replacement document, MongoDB generates adds the_id field with a randomly generated ObjectIdvalue.

Note

You cannot specify different _id field values in thequery parameter and replacement document. If you do, theoperation errors.

For example, the following update sets the upsert option to true:

  1. db.books.update(
  2. { item: "ZZZ135" }, // Query parameter
  3. { // Replacement document
  4. item: "ZZZ135",
  5. stock: 5,
  6. tags: [ "database" ]
  7. },
  8. { upsert: true } // Options
  9. )

If no document matches the <query> parameter, the updateoperation inserts a document with only the replacementdocument. Because no _id field was specified in thereplacement document or query document, the operation creates anew unique ObjectId for the new document’s _id field.You can see the upsert reflected in the WriteResult of the operation:

  1. WriteResult({
  2. "nMatched" : 0,
  3. "nUpserted" : 1,
  4. "nModified" : 0,
  5. "_id" : ObjectId("5da78973835b2f1c75347a83")
  6. })

The operation inserts the following document into the bookscollection (your ObjectId value will differ):

  1. {
  2. "_id" : ObjectId("5da78973835b2f1c75347a83"),
  3. "item" : "ZZZ135",
  4. "stock" : 5,
  5. "tags" : [ "database" ]
  6. }

If no document matches the query criteria and the <update>parameter is a document with update operator expressions, then the operation creates a base documentfrom the equality clauses in the <query> parameter andapplies the expressions from the <update> parameter.

Comparison operations fromthe <query> will not be included in the new document. Ifthe new document does not include the _id field, MongoDBadds the _id field with an ObjectId value.

For example, the following update sets the upsert option to true:

  1. db.books.update(
  2. { item: "BLP921" }, // Query parameter
  3. { // Update document
  4. $set: { reorder: false },
  5. $setOnInsert: { stock: 10 }
  6. },
  7. { upsert: true } // Options
  8. )

If no documents match the query condition, the operationinserts the following document (your ObjectId valuewill differ):

  1. {
  2. "_id" : ObjectId("5da79019835b2f1c75348a0a"),
  3. "item" : "BLP921",
  4. "reorder" : false,
  5. "stock" : 10
  6. }

See also

$setOnInsert

If the <update> parameter is an aggregation pipeline, the update creates a basedocument from the equality clauses in the <query>parameter, and then applies the pipeline to the document tocreate the document to insert. If the new document does notinclude the _id field, MongoDB adds the _id field withan ObjectId value.

For example, the following update sets theupsert option to true:

  1. db.books.update(
  2. { // Query parameter
  3. item: "MRQ014",
  4. ratings: [2, 5, 3]
  5. },
  6. [ // Aggregation pipeline
  7. { // Update document
  8. $set: {
  9. "tags": [ "fiction", "hardcover" ],
  10. "averageRating": { $avg: "$ratings" }
  11. }
  12. }
  13. ],
  14. { upsert: true } // Options
  15. )

If no document matches the <query> parameter, theoperation inserts the following document into the bookscollection (your ObjectId value will differ):

  1. {
  2. "_id" : ObjectId("5da7991c835b2f1c75349ed9"),
  3. "item" : "MRQ014",
  4. "ratings" : [ 2, 5, 3 ],
  5. "tags" : [ "fiction", "hardcover" ],
  6. "averageRating" : 3.3333333333333335
  7. }

See also

For additional examples of updates usingaggregation pipelines, see Update with Aggregation Pipeline.

Combine Upsert and Multi Options (Match)

From the mongo shell, insert the followingdocuments into a books collection:

  1. db.books.insertMany([
  2. {
  3. _id: 5,
  4. item: "RQM909",
  5. stock: 18,
  6. info: { publisher: "0000", pages: 170 },
  7. reorder: true
  8. },
  9. {
  10. _id: 6,
  11. item: "EFG222",
  12. stock: 15,
  13. info: { publisher: "1111", pages: 72 },
  14. reorder: true
  15. }
  16. ])

The following operation specifies both the multi option andthe upsert option. If matching documents exist, theoperation updates all matching documents. If no matchingdocuments exist, the operation inserts a new document.

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

The operation updates all matching documents and results in thefollowing:

  1. {
  2. "_id" : 5,
  3. "item" : "RQM909",
  4. "stock" : 18,
  5. "info" : { "publisher" : "0000", "pages" : 170 },
  6. "reorder" : false,
  7. "tags" : [ "literature", "translated" ]
  8. }
  9. {
  10. "_id" : 6,
  11. "item" : "EFG222",
  12. "stock" : 15,
  13. "info" : { "publisher" : "1111", "pages" : 72 },
  14. "reorder" : false,
  15. "tags" : [ "literature", "translated" ]
  16. }

Combine Upsert and Multi Options (No Match)

If the collection had no matching document, the operationwould result in the insertion of a single document using thefields from both the <query> and the <update>specifications. For example, consider the following operation:

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

The operation inserts the following document into the bookscollection (your ObjectId value will differ):

  1. {
  2. "_id" : ObjectId("5db337934f670d584b6ca8e0"),
  3. "info" : { "publisher" : "Self-Published" },
  4. "reorder" : false,
  5. "stock" : 25,
  6. "tags" : [ "literature", "hardcover" ]
  7. }

When you execute an update() with upsert:true and the query matches no existing document, MongoDB will refuseto insert a new document if the query specifies conditions on the_id field using dot notation.

This restriction ensures that the order of fields embedded in the_id document is well-defined and not bound to the order specified inthe query.

If you attempt to insert a document in this way, MongoDB will raise anerror. For example, consider the following update operation. Since theupdate operation specifies upsert:true and the query specifiesconditions on the _id field using dot notation, then the update willresult in an error when constructing the document to insert.

  1. db.collection.update( { "_id.name": "Robert Frost", "_id.uid": 0 },
  2. { "categories": ["poet", "playwright"] },
  3. { upsert: true } )

The WriteResult of the operation returns the followingerror:

  1. WriteResult({
  2. "nMatched" : 0,
  3. "nUpserted" : 0,
  4. "nModified" : 0,
  5. "writeError" : {
  6. "code" : 111,
  7. "errmsg" : "field at '_id' must be exactly specified, field at sub-path '_id.name'found"
  8. }
  9. })

See also

WriteResult()

Use Unique Indexes

Warning

To avoid inserting the same document more than once,only use upsert: true if the query field is uniquelyindexed.

Given a collection named people where no documents havea name field that holds the value Andy, consider when multipleclients issue the following db.collection.update() withupsert: true at the same time:

  1. db.people.update(
  2. { name: "Andy" }, // Query parameter
  3. { // Update document
  4. name: "Andy",
  5. rating: 1,
  6. score: 1
  7. },
  8. { upsert: true } // Options
  9. )

If all db.collection.update() operations complete thequery portion before any client successfully inserts data, andthere is no unique index on the name field, then each updateoperation may result in an insert.

To prevent MongoDB from inserting the same document more than once,create a unique index on the name field.With a unique index, if multiple applications issue the same updatewith upsert: true, exactly onedb.collection.update() would successfully insert a newdocument.

The remaining operations would either:

  • update the newly inserted document, or

  • fail when they attempted to insert a duplicate.

If the operation fails because of a duplicate index key error,applications may retry the operation which will succeed as an updateoperation.

See also

$setOnInsert

Update with Aggregation Pipeline

Starting in MongoDB 4.2, the db.collection.update() 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).

Modify a Field Using 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.update(
  2. { },
  3. [
  4. { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
  5. { $unset: [ "misc1", "misc2" ] }
  6. ],
  7. { multi: true }
  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.

  • 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" ] }

Perform Conditional Updates Based on Current Field Values

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.update(
  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. { multi: true }
  16. )

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" }

Specify arrayFilters for Array Update Operations

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.

Note

The <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
  2.  
  3. [
  4. { "x.a": { $gt: 85 } },
  5. { "x.b": { $gt: 80 } }
  6. ]

However, you can specify compound conditions on the same identifierin a single filter document, such as in the following examples:

  1. // Example 1
  2. [
  3. { $or: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }
  4. ]
  5. // Example 2
  6. [
  7. { $and: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }
  8. ]
  9. // Example 3
  10. [
  11. { "x.a": { $gt: 85 }, "x.b": { $gt: 80 } }
  12. ]

arrayFilters is not available for updates that use anaggregation pipeline.

Update Elements Match arrayFilters Criteria

To update all array elements which match a specified criteria, use thearrayFilters parameter.

From the mongo shell, create a studentscollection with the following documents:

  1. db.students.insertMany([
  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.update(
  2. { grades: { $gte: 100 } },
  3. { $set: { "grades.$[element]" : 100 } },
  4. {
  5. multi: true,
  6. arrayFilters: [ { "element": { $gte: 100 } } ]
  7. }
  8. )

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

You can also use the arrayFiltersparameter to update specific document fields within an array ofdocuments.

From the mongo shell, create a students2collection with the following documents:

  1. db.students2.insertMany([
  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.update(
  2. { },
  3. { $set: { "grades.$[elem].mean" : 100 } },
  4. {
  5. multi: true,
  6. arrayFilters: [ { "elem.grade": { $gte: 85 } } ]
  7. }
  8. )

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.

From the mongo shell, create a memberscollection 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 touse the index {status: 1 }:

Note

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

  1. db.members.update(
  2. { points: { $lte: 20 }, status: "P" }, // Query parameter
  3. { $set: { misc1: "Need to activate" } }, // Update document
  4. { multi: true, hint: { status: 1 } } // Options
  5. )

The update command returns the following:

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

To see the index used, run explain on the operation:

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

The db.collection.explain().update()does not modify the documents.

Override Default Write Concern

The following operation on a replica set specifies a writeconcern of "w: majority" with awtimeout of 5000 milliseconds such that the method returns afterthe write propagates to a majority of the voting replica set members orthe method times out after 5 seconds.

Changed in version 3.0: In previous versions, majority referred to the majority of allmembers of the replica set instead of the majority of the votingmembers.

  1. db.books.update(
  2. { stock: { $lte: 10 } },
  3. { $set: { reorder: true } },
  4. {
  5. multi: true,
  6. writeConcern: { w: "majority", wtimeout: 5000 }
  7. }
  8. )

Specify Collation

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: {
  2. locale: <string>,
  3. caseLevel: <boolean>,
  4. caseFirst: <string>,
  5. strength: <int>,
  6. numericOrdering: <boolean>,
  7. alternate: <string>,
  8. maxVariable: <string>,
  9. backwards: <boolean>
  10. }

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.

From the mongo shell, create a collection namedmyColl with the following documents:

  1. db.myColl.insertMany(
  2. [
  3. { _id: 1, category: "café", status: "A" },
  4. { _id: 2, category: "cafe", status: "a" },
  5. { _id: 3, category: "cafE", status: "a" }
  6. ])

The following operation includes the collationoption and sets multi to true to update all matching documents:

  1. db.myColl.update(
  2. { category: "cafe" },
  3. { $set: { status: "Updated" } },
  4. {
  5. collation: { locale: "fr", strength: 1 },
  6. multi: true
  7. }
  8. );

The write result of the operation returns the following document, indicating that all three documents in thecollection were updated:

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

After the operation, the collection contains the following documents:

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

WriteResult

Changed in version 2.6.

Successful Results

The db.collection.update() method returns aWriteResult object that contains the status of the operation.Upon success, the WriteResult object contains the number ofdocuments that matched the query condition, the number of documentsinserted by the update, and the number of documents modified:

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

See

WriteResult.nMatched, WriteResult.nUpserted,WriteResult.nModified

Write Concern Errors

If the db.collection.update() method encounters writeconcern errors, the results include theWriteResult.writeConcernError field:

  1. WriteResult({
  2. "nMatched" : 1,
  3. "nUpserted" : 0,
  4. "nModified" : 1,
  5. "writeConcernError" : {
  6. "code" : 64,
  7. "errmsg" : "waiting for replication timed out at shard-a"
  8. }
  9. })

See also

WriteResult.hasWriteConcernError()

Errors Unrelated to Write Concern

If the db.collection.update() method encounters a non-writeconcern error, the results include the WriteResult.writeErrorfield:

  1. WriteResult({
  2. "nMatched" : 0,
  3. "nUpserted" : 0,
  4. "nModified" : 0,
  5. "writeError" : {
  6. "code" : 7,
  7. "errmsg" : "could not contact primary for replica set shard-a"
  8. }
  9. })

See also

WriteResult.hasWriteError()