DB/MongoDB

mongodb - save, insert

linuxism 2014. 5. 8. 12:50


What is the difference between save and insert in Mongo DB? both looks the same

db.users.save({username:"google",password:"google123"})

db.users.insert({username:"google",password:"google123"})



IN your given examples, the behavior is essentially the same.

save behaves differently if it is passed with an "_id" parameter.

If the document contains an _id field, then the save() method performs an upsert querying the collection on the _id field:

If a document does not exist with the specified _id value, the save() method performs an insert with the specified fields in the document.

If a document exists with the specified _id value, the save() method performs an update, replacing all field in the existing record with the fields from the document.
2 
What about save vs update with upsert:true ? –  Jeff Feb 14 at 12:40
3 
both have different syntax. Update takes multiple arguments ({condition},{update to doc}, upsert, multi) whereas save accepts only one argument(_id being the parameter for conditional argument).update can accept any condition but save has the limitation of condition only on the _id field. –  rahulroc Feb 17 at 4:33



save insert or update a document.

insert does only an insertion.

But in your case, it will do the same, as the document provided in save has no _id field.



source - http://stackoverflow.com/questions/16209681/what-is-the-difference-between-save-and-insert-in-mongo-db