Update Documents

In MongoDB, update() method is used to update or modify the existing documents of a collection.

Syntax:

snippet
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example

Consider an example which has a collection name rookienerd. Insert the following documents in collection:

snippet
db.rookienerd.insert(
   {
     course: "java",
     details: {
        duration: "6 months",
        Trainer: "Sonoo jaiswal"
     },
     Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
     category: "Programming language"
   }
)

After successful insertion, check the documents by following query:

snippet
>db.rookienerd.find()

Output:

Output
{ "_id" : ObjectId("56482d3e27e53d2dbc93cef8"), "course" : "java", "details" : { "duration" : "6 months", "Trainer" : "Sonoo jaiswal" }, "Batch" : [ {"size" : "Small", "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ], "category" : "Programming language" }

Update the existing course "java" into "android":

snippet
>db.rookienerd.update({'course':'java'},{$set:{'course':'android'}})

Check the updated document in the collection:

snippet
>db.rookienerd.find()

Output:

Output
{ "_id" : ObjectId("56482d3e27e53d2dbc93cef8"), "course" : "android", "details" : { "duration" : "6 months", "Trainer" : "Sonoo jaiswal" }, "Batch" : [ {"size" : "Small", "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ], "category" : "Programming language" }
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +