MongoDB - Update a Document
Use the update() method or save() method to update documents in MongoDB.
In MongoDB, both the update() method and the save() method can be used to update a document.
The update() method updates values in an existing document or documents, while the save() method replaces a document with the document passed in as a parameter.
However, the update() method can also replace the whole document, depending on the parameter that's passed in.
The update() Method
Here's an example of the update() method.
First, let's select a record to update:
Result:
{
"_id" : 6,
"name" : "Jeff Martin",
"instrument" : "Vocals",
"born" : 1969
}
Jeff actually does a lot more than just sing. So let's add some more instruments. We'll use the $set operator to update a single field.
Result:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Now if we do another query, we see that the document has been updated as specified:
Result:
{
"_id" : 6,
"name" : "Jeff Martin",
"instrument" : [
"Vocals",
"Guitar",
"Sitar"
],
"born" : 1969
}
Some more options:
- If the field does not exist, the
$setoperator will add a new field with the specified value, provided that the new field does not violate a type constraint. - You can also use
{ upsert: true }to create a new document when no document matches the query. - You can use
{ multi: true }to update multiple documents that meet the query criteria. By default, this option is set tofalse, so only one document is updated if you don't set it totrue.
The save() Method
The save() method is a cross between update() and insert(). When you use the save() method, if the document exists, it will be udpated. If it doesn't exist, it will be created.
If you don't specify an _id field, MongoDB will create a document with an _id that contains a ObjectId value (as per an insert()).
If you specify an _id field, it performs an update with { upsert: true }, meaning, it creates a new document if no document matches the query.
We don't currently have any documents in our producers collection. Let's create one using the save() method:
Result:
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 1 })
Now if we search the producers collection, we see our newly created record:
Result:
{ "_id" : 1, "name" : "Bob Rock" }