Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Save and update

Tags:

mongodb

While reading about Mongo Save and Update ,I got bit confuse -as per article

MongoDB's update() and save() methods are used to update document into a collection. The update() method update values in the existing document while the save() method replaces the existing document with the document passed in save() method.

Please let me know difference in both .

like image 521
Vivek Panday Avatar asked Apr 16 '15 06:04

Vivek Panday


2 Answers

update changes an existing document found by your find-parameters and does nothing when no such document exist (unless you use the upsert option).

save doesn't allow any find-parameters. It 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. When the document you insert has no _id field, it generates one with a newly created ObjectId before inserting.

collection.save(document); is basically a shorthand for:

if (document._id == undefined) {
    document._id = new ObjectId();
}
collection.update({ "_id":document._id }, document, { upsert:true });
like image 169
Philipp Avatar answered Nov 11 '22 05:11

Philipp


From the documentation:

Save command.

The save() method uses either the insert or the update command, which use the default write concern. To specify a different write concern, include the write concern in the options parameter.

If the document does not contain an _id field, then the save() method calls the insert() method.

If the document contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field.

Update command

if upsert is not specified it

Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.

If upsert is true and no document matches the query criteria, update() inserts a single document.


So they are pretty similar and both can update and insert the document. The difference is that save can update only one document.

like image 5
Salvador Dali Avatar answered Nov 11 '22 06:11

Salvador Dali