Navigation
This version of the documentation is archived and no longer supported.

db.collection.update()

Definition

db.collection.update(query, update, options)

Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.

By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria.

The update() method has the following form:

Changed in version 2.6.

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

The update() method takes the following parameters:

Parameter Type Description
query document The selection criteria for the update. Use the same query selectors as used in the find() method.
update document The modifications to apply. For details see Update Parameter.
upsert boolean Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.
multi boolean Optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false. For additional information, see Multi Parameter.
writeConcern document

Optional. A document expressing the write concern. Omit to use the default write concern. See Safe Writes.

New in version 2.6.

Changed in version 2.6: The update() method returns an object that contains the status of the operation.

Returns:A WriteResult object that contains the status of the operation.

Behavior

Safe Writes

Changed in version 2.6.

The update() method uses the update command, which uses the default write concern. To specify a different write concern, include the writeConcern option in the options parameter. See Override Default Write Concern for an example.

Update Parameter

The update() method either modifies specific fields in existing documents or replaces an existing document entirely.

Update Specific Fields

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

  • The <update> document must contain only update operator expressions.
  • The update() method updates only the corresponding 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 in an array, use dot notation to specify the field.

Replace a Document Entirely

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

Upsert Option

Upsert Behavior

If upsert is true and no document matches the query criteria, update() inserts a single document. The update creates the new document with either:

  • The fields and values of the <update> parameter if the <update> parameter contains only field and value pairs, or
  • The fields and values of both the <query> and <update> parameters if the <update> parameter contains update operator expressions. The update creates a base document from the equality clauses in the <query> parameter, and then applies the update expressions from the <update> parameter.

If upsert is true and there are documents that match the query criteria, update() performs an update.

See also

$setOnInsert

Use Unique Indexes

Warning

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

Given a collection named people where no documents have a name field that holds the value Andy. Consider when multiple clients issue the following update with upsert: true at the same time:

db.people.update(
   { name: "Andy" },
   {
      name: "Andy",
      rating: 1,
      score: 1
   },
   { upsert: true }
)

If all 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.

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 update with upsert: true, exactly one update() would successfully insert a new document.

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 update operation.

Multi Parameter

If multi is set to true, the update() method updates all documents that meet the <query> criteria. The multi update operation may interleave with other operations, both read and/or write operations. For unsharded collections, you can override this behavior with the $isolated operator, which isolates the update operation and disallows yielding during the operation. This isolates the update so that no client can see the updated documents until they are all processed, or an error stops the update operation.

If the <update> document contains only field:value expressions, then update() cannot update multiple documents.

For an example, see Update Multiple Documents.

Sharded Collections

All update() operations for a sharded collection that specify the multi: false option must include the shard key or the _id field in the query specification. update() operations specifying multi: false in a sharded collection without the shard key or the _id field return an error.

See also

findAndModify()

Examples

Update Specific Fields

To update specific fields in a document, use update operators in the <update> parameter.

For example, given a books collection with the following document:

{
  _id: 1,
  item: "TBD",
  stock: 0,
  info: { publisher: "1111", pages: 430 },
  tags: [ "technology", "computer" ],
  ratings: [ { by: "ijk", rating: 4 }, { by: "lmn", rating: 5 } ],
  reorder: false
}

The following operation uses:

  • the $inc operator to increment the stock field; and
  • the $set operator to replace the value of the item field, the publisher field in the info embedded document, the tags field, and the second element in the ratings array.
db.books.update(
   { _id: 1 },
   {
     $inc: { stock: 5 },
     $set: {
       item: "ABC123",
       "info.publisher": "2222",
       tags: [ "software" ],
       "ratings.1": { by: "xyz", rating: 3 }
     }
   }
)

The updated document is the following:

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

Remove Fields

The following operation uses the $unset operator to remove the tags field:

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

Replace All Fields

Given the following document in the books collection:

{
  _id: 2,
  item: "XYZ123",
  stock: 15,
  info: { publisher: "5555", pages: 150 },
  tags: [ ],
  ratings: [ { by: "xyz", rating: 5, comment: "ratings and reorder will go away after update"} ],
  reorder: false
}

The following operation passes an <update> document that contains only field and value pairs. The <update> document completely replaces the original document except for the _id field.

db.books.update(
   { item: "XYZ123" },
   {
     item: "XYZ123",
     stock: 10,
     info: { publisher: "2255", pages: 150 },
     tags: [ "baking", "cooking" ]
   }
)

The updated document contains only the fields from the replacement document and the _id field. That is, the fields ratings and reorder no longer exist in the updated document since the fields were not in the replacement document.

{
   "_id" : 2,
   "item" : "XYZ123",
   "stock" : 10,
   "info" : { "publisher" : "2255", "pages" : 150 },
   "tags" : [ "baking", "cooking" ]
}

Insert a New Document if No Match Exists

The following update sets the upsert option to true so that update() creates a new document in the books collection if no document matches the <query> parameter:

db.books.update(
   { item: "ZZZ135" },
   {
     item: "ZZZ135",
     stock: 5,
     tags: [ "database" ]
   },
   { upsert: true }
)

If no document matches the <query> parameter, the update operation inserts a document with only the fields and values of the <update> document and a new unique ObjectId for the _id field:

{
  "_id" : ObjectId("542310906694ce357ad2a1a9"),
  "item" : "ZZZ135",
  "stock" : 5,
  "tags" : [ "database" ]
}

For more information on upsert option and the inserted document, Upsert Option.

Update Multiple Documents

To update multiple documents, set the multi option to true. For example, the following operation updates all documents where stock is less than or equal to 10:

db.books.update(
   { stock: { $lte: 10 } },
   { $set: { reorder: true } },
   { multi: true }
)

If the reorder field does not exist in the matching document(s), the $set operator will add the field with the specified value. See $set for more information.

Override Default Write Concern

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 replica set members or the method times out after 5 seconds.

db.books.update(
   { stock: { $lte: 10 } },
   { $set: { reorder: true } },
   {
     multi: true,
     writeConcern: { w: "majority", wtimeout: 5000 }
   }
)

Combine the upsert and multi Options

Given a books collection that includes the following documents:

{
  _id: 5,
  item: "EFG222",
  stock: 18,
  info: { publisher: "0000", pages: 70 },
  reorder: true
}
{
  _id: 6,
  item: "EFG222",
  stock: 15,
  info: { publisher: "1111", pages: 72 },
  reorder: true
}

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

db.books.update(
   { item: "EFG222" },
   { $set: { reorder: false, tags: [ "literature", "translated" ] } },
   { upsert: true, multi: true }
)

The operation updates all matching documents and results in the following:

{
   "_id" : 5,
   "item" : "EFG222",
   "stock" : 18,
   "info" : { "publisher" : "0000", "pages" : 70 },
   "reorder" : false,
   "tags" : [ "literature", "translated" ]
}
{
   "_id" : 6,
   "item" : "EFG222",
   "stock" : 15,
   "info" : { "publisher" : "1111", "pages" : 72 },
   "reorder" : false,
   "tags" : [ "literature", "translated" ]
}

If the collection had no matching document, the operation would result in the insertion of a document using the fields from both the <query> and the <update> specifications:

{
   "_id" : ObjectId("5423200e6694ce357ad2a1ac"),
   "item" : "EFG222",
   "reorder" : false,
   "tags" : [ "literature", "translated" ]
}

For more information on upsert option and the inserted document, Upsert Option.

WriteResult

Changed in version 2.6.

Successful Results

The update() method returns a WriteResult object that contains the status of the operation. 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({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Write Concern Errors

If the update() method encounters write concern errors, the results include the WriteResult.writeConcernError field:

WriteResult({
   "nMatched" : 1,
   "nUpserted" : 0,
   "nModified" : 1,
   "writeConcernError" : {
      "code" : 64,
      "errmsg" : "waiting for replication timed out at shard-a"
   }
})

Errors Unrelated to Write Concern

If the update() method encounters a non-write concern error, the results include the WriteResult.writeError field:

WriteResult({
   "nMatched" : 0,
   "nUpserted" : 0,
   "nModified" : 0,
   "writeError" : {
      "code" : 7,
      "errmsg" : "could not contact primary for replica set shard-a"
   }
})