top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

MongoDB: What is the use of update and save methods within mongoDB ?

+3 votes
542 views
MongoDB: What is the use of update and save methods within mongoDB ?
posted Jun 28, 2015 by Harshita

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Every DBMS support various functions to do various type of operations like insertion, deletion , retrieve records/documents.
MongoDB is also a data base management system which maintains the data in efficient way. It is flexible in various terms compare to SQL.

"update" is one of the method defined in mongoDB system that is used to update a particular field of a document while "save" method is used to replace a document with the existing one.
Note: If document doesn't exist then a new document will be created and inserted into collection.

answer Jun 28, 2015 by Neeraj Mishra
+1 vote

In case of save method, checks if there is a document with the same _id as the one you save exists. When it exists, it replaces it. When no such document exists, it inserts the document as a new one.
while update,changes an existing document found by find-parameters and does nothing when no such document exist
The update() method updates values in the existing document.
syntax for update command:

>db.Collection_name.update(Selection_Criteria,Update_data);

Consider the mycol collectioin has following data.

  >db.Collection_name.find(); 
    { "_id" : ObjectId(5983548781331adf45ec5), "title":"Queryhome"};
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"Tech Home"};
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"GK-Tech-Chill"};

then
db.Collection_name.update({"title":"Queryhome"},{$set:{"title":"Queryhome media solutions"}});
then execute this command

>db.Collection_name.find();

you will see-

 { "_id" : ObjectId(5983548781331adf45ec5), "title":"Queryhome media solutions"};
    { "_id" : ObjectId(5983548781331adf45ec6), "title":"Tech Home"};
    { "_id" : ObjectId(5983548781331adf45ec7), "title":"GK-Tech-Chill"};

But In case of save:
The save() method replaces the existing document with the new document passed in save() method.

>db.Collection_name.save({_id:ObjectId(),NEW_DATA});

Following example will replace the document with the _id '5983548781331adf45ec7'

>db.Collection_name.save(
   {
      "_id" : ObjectId(5983548546431adf45ec7), "title":"Tech Solutions",
         "by":"Queryhome"
   }
)
>db.Collection_name.find()
{ "_id" : ObjectId(5983548546431adf45ec7), "title":"Tech Solutions",
   "by":"Queryhome"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"GK home"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tech-GK-Chill"}
answer Feb 7, 2016 by Shivam Kumar Pandey
...