MongoDB Save and Update

While reading about Mongo Save and Update, I got a little confused - in the article

To update a document into the collection, the update () and save () methods of MongoDB are used. The update () method updates the values โ€‹โ€‹of the method in an existing document, while the save () method replaces the existing document with the document passed by the save () method.

Please let me know the difference in both.

+6
source share
2 answers

update modifies an existing document found by your search parameters and does nothing when such a document does not exist (unless you use the upsert parameter).

save does not allow to find search parameters. It checks for a document with the same _id as the one you are saving. When it exists, it replaces it. When there is no such document, it inserts the document as new. When the document you are _id does not have a _id field, it generates one with the newly created ObjectId before pasting.

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

 if (document._id == undefined) { document._id = new ObjectId(); } collection.update({ "_id":document._id }, document, { upsert:true }); 
+9
source

From the documentation:

Save the team.

The save () method uses either the insert command or the update command, which use the default write problem. To indicate another recording problem, include the recording problem in the parameter parameter.

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

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

Refresh Team

if upsert is not specified

Modifies an existing document or documents in a collection. The method can modify certain fields of an existing document or documents or completely replace an existing document, depending on the update Parameter.

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


Thus, they are pretty similar, and both can update and insert a document. The difference is that save can only update one document.

+1
source

Source: https://habr.com/ru/post/985240/


All Articles