Untitled 9

MongoDB Update() With Examples

In this tutorial we will understand how to use db.collection.update()for updating documents in MongoDB database effectively. We need to understand what does it do? The db.collection.update() is used to modify documents of a collection in our collections. Also, it will update just a single document by default. We can also use it to modify more than one document by specifying the query at the same time by using multi: true.

Single Document
Let’s assume our collection ‘Pets’ has these documents:

{ "_id" : 1, "name" : "Wag", "type" : "Dog" }
{ "_id" : 2, "name" : "Bark", "type" : "Dog" }
{ "_id" : 3, "name" : "Meow", "type" : "Cat" }

Now let’s update a single document in it

db.pets.update(
{ type: "Dog" },
{ $set: { type: "Cow" } }
)

Result

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

We have updated just a single document in the above example. Now we will query our collection update in MongoDB database to confirm it.

db.pets.find()

Result

{ "_id" : 1, "name" : "Wag", "type" : "Cow" }
{ "_id" : 2, "name" : "Bark", "type" : "Dog" }
{ "_id" : 3, "name" : "Meow", "type" : "Cat" }

Multiple Documents

We saw that we changed ‘type’ which is effectively changed. Now we will change multiple documents and then query the collection.

{ "_id" : 1, "name" : "Wag", "type" : "Dog" }
{ "_id" : 2, "name" : "Bark", "type" : "Dog" }
{ "_id" : 3, "name" : "Meow", "type" : "Cat" }

Now we are going to add multi: true

db.pets.update(
{ type: "Dog" },
{ $set: { type: "Cow" } },
{ multi: true }
)

Result

WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

You can we updated two documents at the same time. See how our collection appears after that

db.pets.find()

Result

{ "_id" : 1, "name" : "Wag", "type" : "Cow" }
{ "_id" : 2, "name" : "Bark", "type" : "Cow" }
{ "_id" : 3, "name" : "Meow", "type" : "Cat" }

Upsert Operation

We can use upsert as well with db.collection.update() method. When upsert: true it gets updated otherwise a new document is inserted.

So this was our first collection with its documents. We will use it again.

{ "_id" : 1, "name" : "Wag", "type" : "Dog" }
{ "_id" : 2, "name" : "Bark", "type" : "Dog" }
{ "_id" : 3, "name" : "Meow", "type" : "Cat" }

Check this example

 db.pets.update(
{ name: "Bubbles" },
{ $set: { type: "Fish" } },
{ upsert: true }
)

Result

WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5fe2c925d9914101694102e1")
})

There was no match so the document is upserted

See here

db.pets.find()

Result

{ "_id" : 1, "name" : "Wag", "type" : "Dog" }
{ "_id" : 2, "name" : "Bark", "type" : "Dog" }
{ "_id" : 3, "name" : "Meow", "type" : "Cat" }
{ "_id" : ObjectId("5fe2c925d9914101694102e1"), "name" : "Bubbles", "type" : "Fish" }

Embedded Documents

We can update embedded documents usingdb.collection.update()

See this example for the mentioned document here:

{
"_id" : 1,
"name" : "Wag",
"type" : "Dog",
"specs" : {
"height" : 400,
"weight" : 15,
"color" : "brown"
}
}

We can use the following code to update the embedded document. Now we will the function to update it.

db.pets.update({
_id: 1
}, {
$set: {
"specs.weight": 20,
"specs.color": "blue"
}
})

Result

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

We can see the modification now as one document matched. We will confirm it by querying it.

db.pets.find({
_id: 1
}).pretty()db.pets.find({
_id: 1
}).pretty()

Result

The specified document has been updated duly.

{
"_id" : 1,
"name" : "Wag",
"type" : "Dog",
"specs" : {
"height" : 400,
"weight" : 20,
"color" : "blue"
}
}

Arrays

For arrays we can use the same db.collection.update()to update

Check this document for instance.

{
"_id" : 1,
"name" : "Wag",
"type" : "Dog",
"awards" : [
"Top Dog",
"Best Dog",
"Biggest Dog"
]
}

We are going to update two array elements using db.collection.update()

db.pets.update({
_id: 1
}, {
$set: {
"name": "Bark",
"awards.0": "Bottom Dog",
"awards.1": "Worst Dog"
}
})

Result

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

You will notice that a document has been modified. Lets query it to confirm the changes

db.pets.find().pretty()

Result

{
"_id" : 1,
"name" : "Bark",
"type" : "Dog",
"awards" : [
"Bottom Dog",
"Worst Dog",
"Biggest Dog"
]
}

The arrayFilters Parameter

We can also filter queries and find which array elements to update by using arrayFilters with the positional $ operator. Let’s see the following collection Players for more:

{ "_id" : 1, "scores" : [ 1, 5, 3 ] }
{ "_id" : 2, "scores" : [ 8, 17, 18 ] }
{ "_id" : 3, "scores" : [ 15, 11, 8 ] }

We will use the same db.players.update to update array elements with a higher value than our limit parameter 10.

db.players.update(
{ scores: { $gte: 10 } },
{ $set: { "scores.$[e]" : 10 } },
{ arrayFilters: [ { "e": { $gte: 10 } } ] }
)

Here is the result

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

You will notice only one document has been updated despite the fact that two of them matched the criteria. It was because we did not specify multi: true

Let’s see the changes using

db.players.find()

Result

{ "_id" : 1, "scores" : [ 1, 5, 3 ] }
{ "_id" : 2, "scores" : [ 8, 10, 10 ] }
{ "_id" : 3, "scores" : [ 15, 11, 8 ] }

Here two elements are modified of Document 2 due to specific match

More Information

We can also use other parameters withdb.collection.update() like writeConcern, collation, and hint. Let’s know for future queries about about MongoDB update() to modify or upsert documents in our collections.