OPTIONS

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 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() 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 expressions, such those using the $set operator, then:

  • The <update> document must contain only update operator expressions.
  • The update() method updates only the corresponding fields in the document. For an example, see Update Specific Fields.

Replace Document Entirely

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

  • The update() method replaces the matching document with the <update> document. The update() method does not replace the _id value. For an example, see Replace All Fields.
  • update() cannot update multiple documents.

Upsert Parameter

Upsert Use

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

  • The fields and values of the <update> parameter, or
  • The fields and values of the both the <query> and <update> parameters. The upsert creates a document with data from both <query> and <update> if the <update> parameter contains only update operator expressions.

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

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 operation at the same time. The following operation becomes an insert because the upsert flag is true.:

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 perform 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 an applications issues a group of upsert operations, 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 write operations. For unsharded collections, you can override this behavior with the $isolated isolation operator, which isolates the update operation and blocks other write operations during the update.

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.

Examples

Update Specific Fields

To update specific fields in a document, use update operators in the <update> parameter. If the <update> parameter refers to fields non-existent in the current document, the update() method adds the fields to the document.

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

{ "_id" : 11, "item" : "Divine Comedy", "stock" : 2 }

The following operation adds a price field to the document and increments the stock field by 5.

db.books.update(
   { item: "Divine Comedy" },
   {
      $set: { price: 18 },
      $inc: { stock: 5 }
   }
)

The updated document is now the following:

{ "_id" : 11, "item" : "Divine Comedy", "price" : 18, "stock" : 7 }

Remove Fields

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

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

Replace All Fields

Given the following document in the books collection:

{
    "_id" : 22,
    "item" : "The Banquet",
    "author" : "Dante",
    "price" : 20,
    "stock" : 4
}

The following operation passes an <update> document that contains only field and value pairs, which means the document replaces all the fields in the original document. The operation does not replace the _id value. The operation contains the same value for the item field in both the <query> and <update> documents, which means the field does not change:

db.books.update(
   { item: "The Banquet" },
   { item: "The Banquet", price: 19 , stock: 3 }
)

The operation creates the following new document. The operation removed the author field and changed the values of the price and stock fields:

{
    "_id" : 22,
    "item" : "The Banquet",
    "price" : 19,
    "stock" : 3
}

Insert a New Document if No Match Exists (Upsert)

The following command 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: "The New Life" },
   { item: "The New Life", author: "Dante", price: 15 },
   { upsert: true }
)

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

{
    "_id" : ObjectId("51e5990c95098ed69d4a89f2"),
    "author" : "Dante",
    "item" : "The New Life",
    "price" : 15
}

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 5:

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

Override Default Write Concern

The following operation to 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: { $lt: 5 } },
   { $set: { reorder: true } },
   {
     multi: true,
     writeConcern: { w: "majority", wtimeout: 5000 }
   }
)

Combine the Upsert and Multi Parameters

Given a books collection that includes the following documents:

{ _id: 11, author: "Dante", item: "Divine Comedy", price: 18 }
{ _id: 22, author: "Dante", item: "The Banquet", price: 19 }
{ _id: 33, author: "Dante", item: "Monarchia", price: 14 }

The following command uses the multi parameter to update all documents where author is "Dante" and uses the upsert parameter to create a new document if no such documents are found:

db.books.update(
   { author: "Dante" },
   { $set: { born: "Florence", died: "Ravenna" } },
   { upsert: true, multi: true }
)

The operation results in the following:

{
    "_id" : 11,
    "author" : "Dante",
    "born" : "Florence",
    "died" : "Ravenna",
    "item" : "Divine Comedy",
    "price" : 18
}
{
    "_id" : 22,
    "author" : "Dante",
    "born" : "Florence",
    "died" : "Ravenna",
    "item" : "The Banquet",
    "price" : 19
}
{
    "_id" : 33,
    "author" : "Dante",
    "born" : "Florence",
    "died" : "Ravenna",
    "item" : "Monarchia",
    "price" : 14
}

Update Arrays

Update an Element by Position

If the update operation requires an update of an element in an array field, the update() method can perform the update using the position of the element and dot notation. Arrays in MongoDB are zero-based.

The following operation queries the bios collection for the first document with _id field equal to 1 and updates the second element in the contribs array:

db.bios.update(
   { _id: 1 },
   { $set: { "contribs.1": "ALGOL 58" } }
)

Update an Element if Position is Unknown

If the position in the array is not known, the update() method can perform the update using the $ positional operator. The array field must appear in the <query> parameter in order to determine which array element to update.

The following operation queries the bios collection for the first document where the _id field equals 3 and the contribs array contains an element equal to compiler. If found, the update() method updates the first matching element in the array to A compiler in the document:

db.bios.update(
   { _id: 3, "contribs": "compiler" },
   { $set: { "contribs.$": "A compiler" } }
)

Update a Document Element

The update() method can perform the update of an array that contains subdocuments by using the positional operator (i.e. $) and the dot notation.

The following operation queries the bios collection for the first document where the _id field equals 6 and the awards array contains a subdocument element with the by field equal to ACM. If found, the update() method updates the by field in the first matching subdocument:

db.bios.update(
   { _id: 6, "awards.by": "ACM"  } ,
   { $set: { "awards.$.by": "Association for Computing Machinery" } }
)

Add an Element

The following operation queries the bios collection for the first document that has an _id field equal to 1 and adds a new element to the awards field:

db.bios.update(
   { _id: 1 },
   {
     $push: { awards: { award: "IBM Fellow", year: 1963, by: "IBM" } }
   }
)

In the next example, the $set operator uses dot notation to access the middle field in the name subdocument. The $push operator adds another document as element to the field awards.

Consider the following operation:

db.bios.update(
   { _id: 1 },
   {
      $set: { "name.middle": "Warner" },
      $push: { awards: {
         award: "IBM Fellow",
            year: "1963",
            by: "IBM"
         }
      }
   }
)

This update() operation:

  • Modifies the field name whose value is another document. Specifically, the $set operator updates the middle field in the name subdocument. The document uses dot notation to access a field in a subdocument.
  • Adds an element to the field awards, whose value is an array. Specifically, the $push operator adds another document as element to the field awards.

WriteResult

Changed in version 2.6.

Successful Results

The update() returns a WriteResult object that contains the status of the operation. Upon success, the WriteResult object contains information on the number of documents that matched the query condition, the number of documents inserted via an upsert, 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"
   }
})