- MongoDB CRUD Operations >
- MongoDB CRUD Tutorials >
- Modify Documents
Modify Documents¶
In MongoDB, both db.collection.update() and
db.collection.save() 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,
db.collection.save() 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.
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:
For further examples, see save().