In
previous post, we have seen, update method replaces entire document, which is
not acceptable in all cases. So in order to update specific field use $set
operator.
> db.employee.find() { "_id" : 1, "firstName" : "Jessi" } { "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies" ] } { "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu", "salary" : 65000, "hobbies" : [ "climbing hills", "dancing", "singing" ] } { "_id" : 4, "firstName" : "Hari Krishna", "lastName" : "Gurram", "age" : 25 } { "_id" : 5, "firstName" : "RamaKrishna", "lastName" : "Gurram", "salary" : 150000, "hobbies" : [ "hackning sites", "Reading books", "listening music" ] } { "_id" : 6, "firstName" : "BalaKrishna", "lastName" : "Gurram", "salary" : 80000, "hobbies" : [ "roaming around", "eating food" ] } { "_id" : ObjectId("54ba2de1f1c8f2149c000740"), "name" : "Krishna", "project" : "A350" } { "_id" : ObjectId("54ba2dfcf1c8f2149c000741"), "name" : "Krishna", "project" : 4 } { "_id" : ObjectId("54ba47c9f1c8f2149c000742"), "name" : "Keerthi", "hobbies" : [ "watching movies", "playing games", "cooking" ] }
Syntax
{
$set: { <field1>: <value1>, ... } }
1. Update employee lastName
as “Amara” and add field “age” where “_id” is 5.
> db.employee.update({"_id" : 5}, {$set : {"lastName":"Amara", "age" : 30}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > > > db.employee.find() { "_id" : 1, "firstName" : "Jessi" } { "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies" ] } { "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu", "salary" : 65000, "hobbies" : [ "climbing hills", "dancing", "singing" ] } { "_id" : 4, "firstName" : "Hari Krishna", "lastName" : "Gurram", "age" : 25 } { "_id" : 5, "firstName" : "RamaKrishna", "lastName" : "Amara", "salary" : 150000, "hobbies" : [ "hackning sites", "Reading books", "listening music" ], "age" : 30 } { "_id" : 6, "lastName" : "Amara", "age" : 31 } { "_id" : ObjectId("54ba2de1f1c8f2149c000740"), "name" : "Krishna", "project" : "A350" } { "_id" : ObjectId("54ba2dfcf1c8f2149c000741"), "name" : "Krishna", "project" : 4 } { "_id" : ObjectId("54ba47c9f1c8f2149c000742"), "name" : "Keerthi", "hobbies" : [ "watching movies", "playing games", "cooking" ] }
By
default $set operator adds a field, if it not exist in the document.
No comments:
Post a Comment