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

Modify Documents

In MongoDB, both db.collection.update() and modify existing documents in a collection. db.collection.update() provides additional control over the modification. For example, you can modify existing data or modify a group of documents that match a query with db.collection.update(). Alternately, replaces an existing document with the same _id field.

This document provides examples of the update operations using each of the two methods in the mongo shell.

Modify Multiple Documents with update() Method

By default, the update() method updates a single document that matches its selection criteria. Call the method with the multi option set to true to update multiple documents. [1]

The following example finds all documents with type equal to "book" and modifies their qty field by -1. The example uses $inc, which is one of the update operators available.

   { type : "book" },
   { $inc : { qty : -1 } },
   { multi: true }

For more examples, see update().

[1]This shows the syntax for MongoDB 2.2 and later. For syntax for versions prior to 2.2, see update().

Modify a Document with save() Method

The save() method can replace an existing document. To replace a document with the save() method, pass the method a document with an _id field that matches an existing document.

The following example completely replaces the document with the _id equal to 10 in the inventory collection:
     _id: 10,
     type: "misc",
     item: "placard"

For further examples, see save().