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

Mongodb

Mongodb Problem Overview


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"})

Mongodb Solutions


Solution 1 - Mongodb

Save Vs Insert :

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

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

For save, If the document contains _id, it will upsert querying the collection on the _id field, If not, it will insert.

> 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.


Save vs Update :

update modifies an existing document matched with your query params. If there is no such matching document, that's when upsert comes in picture.

  • upsert : false : Nothing happens when no such document exist
  • upsert : true : New doc gets created with contents equal to query params and update params

save : Doesn't allow any query-params. if _id exists and there is a matching doc with the same _id, it replaces it. When no _id specified/no matching document, it inserts the document as a new one.

Solution 2 - Mongodb

Let us consider the two cases here for save :-

  1. Having _id in doc.

  2. Not having _id in doc.

                         Save ()
                         /     \
                        /       \
    
                  Having _id     Not Having _id 
    

    ->In this case save will do -> It will do normal insertion upsert to insert.Now in this case as insert() do. what that means, it means take the document and replace the complete document having same _id.

Let us consider the two cases here for insert:-

  1. Having _id of doc in collection.

  2. Not having _id of doc in collection.

                         Insert()
                        /        \
                       /          \
    
    Doc Having _id in collection    Doc Not Having _id 
    

    -> E11000 duplicate key ->Insert a new doc inside the collection. error index:

Solution 3 - Mongodb

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.

Solution 4 - Mongodb

By giving an example

Save an Apple

db.fruit.save({"name":"apple", "color":"red","shape":"round"})
WriteResult({ "nInserted" : 1 })

db.fruit.find();

{
	"_id" : ObjectId("53fa1809132c1f084b005cd0"),
	"color" : "red",
	"shape" : "round",
	"name" : "apple"
}

Save an apple with _id of previously saved apple

db.fruit.save(
{"_id" : ObjectId("53fa1809132c1f084b005cd0"),"name":"apple", 
"color":"real red","shape":"round"})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now the apple we saved has, color updated from red to real red

db.fruit.find();
{
	"_id" : ObjectId("53fa1809132c1f084b005cd0"),
	"color" : "real red",
	"shape" : "round",
	"name" : "apple"
}

Save an apple with _id

db.fruit.save({"_id" : ObjectId("55551809132c1f084b005cd0"),
"name":"apple", "color":"real red","shape":"round"})

    WriteResult({ "nMatched" : 0, "nUpserted" : 1, 
"nModified" : 0, "_id": 55551809132c1f084b005cd0 })

Apple got inserted as there is no apple with the same Object Id to do an update

Insert an Orange

db.fruit.insert({"name":"orange", "color":"orange","shape":"round"})
WriteResult({ "nInserted" : 1 })

Orange is inserted

db.fruit.find();
{
	"_id" : ObjectId("53fa1809132c1f084b005cd0"),
	"color" : "real red",
	"shape" : "round",
	"name" : "apple"
}
{
	"_id" : ObjectId("53fa196d132c1f084b005cd7"),
	"color" : "orange",
	"shape" : "round",
	"name" : "orange"
}
{
	"_id" : ObjectId("55551809132c1f084b005cd0"),
	"color" : "real red",
	"shape" : "round",
	"name" : "apple"
}

So save will act as an update if supplied with an object id, provided the object id already exists other wise it does an insert.

Solution 5 - Mongodb

If you attempt to use "insert" with an ID that was previously used in the same collection you will get a duplicate key error. If you use "save" with an ID that is already in the same collection, it will get updated/overwritten.

If you are looking to do a true update I would suggest using "update". Update will not overwrite in the way Save would if you are Saving using the same ID that is already in the collection.

For example you have two fields "x" and "y" and you want to keep both but change the value of "x". If you chose the "save" command and did not include y with the previous value or not have y at all in your save, then y would no longer have the same value or be there. However if you chose to update using $set and only had x included in your update statement, you would not affect y.

Solution 6 - Mongodb

As you can see here, the save method will essentially do an upsert (update if it finds the doc, insert otherwise):

http://docs.mongodb.org/manual/reference/method/db.collection.save/#db.collection.save

Insert is just that, a straight insert.

Solution 7 - Mongodb

Consider the below document

{ "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" }

if db already contains the document with _id:1, then

save operation will throw the exception like below

E11000 duplicate key error index ...........

and where as insert operation , will just override the document.

Solution 8 - Mongodb

In terms of ORACLE: mongo insert => Oracle insert mongo save => Oracle merge

Solution 9 - Mongodb

db.<collection_name>.save(<Document>) is equivalent to InsertOrUpdate Query.

While, db.<collection_name>.insert(<Document>) is equivalent to just Insert Query.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2093576View Question on Stackoverflow
Solution 1 - MongodbRahulView Answer on Stackoverflow
Solution 2 - MongodbsquiroidView Answer on Stackoverflow
Solution 3 - MongodbAurélien BView Answer on Stackoverflow
Solution 4 - MongodbAbhiView Answer on Stackoverflow
Solution 5 - MongodbRoganRicheartView Answer on Stackoverflow
Solution 6 - MongodbAdam ComerfordView Answer on Stackoverflow
Solution 7 - MongodbBravoView Answer on Stackoverflow
Solution 8 - MongodbJaganView Answer on Stackoverflow
Solution 9 - MongodbVijet BadigannavarView Answer on Stackoverflow