By
default update query updates single document that match given query. To update all
the documents that matche given query, use multi option.
> db.employee.find() { "_id" : 1, "firstName" : "Jessi", "hobbies" : [ "climbing hills" ] } { "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies", "climbing hills" ] } { "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu" } { "_id" : 4, "firstName" : "Hari Krishna", "lastName" : "Gurram", "age" : 25 } { "_id" : 6, "lastName" : "Amara", "age" : 31 } { "_id" : ObjectId("54ba9242f048afaff2a00317"), "firstName" : "Murthy", "lastName" : "Krishna", "age" : 30 }
Let’s
say, I want to add a field “project” to the employee collection, if you update
without multi option, then it updates only one document.
> db.employee.update({}, {$set : {"project" : ""}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > > db.employee.find() { "_id" : 1, "firstName" : "Jessi", "hobbies" : [ "climbing hills" ], "project" : "" } { "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies", "climbing hills" ] } { "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu" } { "_id" : 4, "firstName" : "Hari Krishna", "lastName" : "Gurram", "age" : 25 } { "_id" : 6, "lastName" : "Amara", "age" : 31 } { "_id" : ObjectId("54ba9242f048afaff2a00317"), "firstName" : "Murthy", "lastName" : "Krishna", "age" : 30 }
To
add “project” field to all the employees, use multi option.
> db.employee.update({}, {$set : {"project" : ""}}, {"multi" : true}) WriteResult({ "nMatched" : 6, "nUpserted" : 0, "nModified" : 5 }) > > db.employee.find() { "_id" : 1, "firstName" : "Jessi", "hobbies" : [ "climbing hills" ], "project" : "" } { "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies", "climbing hills" ], "project" : "" } { "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu", "project" : "" } { "_id" : 4, "firstName" : "Hari Krishna", "lastName" : "Gurram", "age" : 25, "project" : "" } { "_id" : 6, "lastName" : "Amara", "age" : 31, "project" : "" } { "_id" : ObjectId("54ba9242f048afaff2a00317"), "firstName" : "Murthy", "lastName" : "Krishna", "age" : 30, "project" : "" }
No comments:
Post a Comment