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:

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" }