Lets use $set operator along with update() method, to update the documents.
test database, names collection
> db.names.find()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
Related Read: Update Method: MongoDB
Lets update the first document using only update method.
> db.names.update({"name": "Alia"}, {"name": "Alia", "age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{
"_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"),
"name" : "Alia",
"age" : 25
}
Everything is ok in this case. But what if you forget to mention the name field in the second argument of update() method.
> db.names.update({"name": "Alia"}, {"age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
In this case, the name field gets erased. As we did not specify name field in the second parameter of update() method.
Using $set operator
> db.names.update({"name": "Bebo"}, {$set: {"age": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
"_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
"name" : "Bebo",
"age" : 25
}
Here we make use of document with name as Bebo. Using $set operator we only specify the fields we want to add or update. Need not specify other existing fields in order to retain them.
Update with SET Operator: MongoDB
> db.names.update({"name": "Bebo"}, {$set: {"age": 25, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
"_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
"name" : "Bebo",
"age" : 25,
"salary" : 25
}
> db.names.update({"name": "Bebo"}, {$set: {"age": 26, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
"_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
"name" : "Bebo",
"age" : 26,
"salary" : 25
}
> db.names.update({"name": "Bebo"}, {$set: {"salary": 30}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
"_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
"name" : "Bebo",
"age" : 26,
"salary" : 30
}
We can update existing field or add a field to the existing document using $set operator and need not to worry about the other fields in the document.