180

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"})
user2093576
  • 3,082
  • 7
  • 32
  • 43

9 Answers9

174

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.

Community
  • 1
  • 1
Rahul
  • 15,979
  • 4
  • 42
  • 63
  • 9
    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. – Rahul Feb 17 '14 at 04:33
  • 1
    As of version 2.6, save has a second argument taking a document expressing the write concern. http://docs.mongodb.org/manual/reference/method/db.collection.save/ – huggie Jul 26 '14 at 09:00
117

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:       
squiroid
  • 13,809
  • 6
  • 47
  • 67
  • 30
    Next level diagrams – John Spiteri Mar 13 '16 at 02:35
  • 9
    Upvoted for the time taken to neatly draw and present the diagrams. – fanbondi Jun 10 '16 at 10:52
  • 3
    gg diagrams there – CᴴᴀZ Oct 14 '21 at 13:44
  • 1
    [Note](https://docs.mongodb.com/v4.4/reference/method/db.collection.save/): Starting in MongoDB 4.2, the `db.collection.save()` method is deprecated. Use [`db.collection.insertOne()`](https://docs.mongodb.com/v4.4/reference/method/db.collection.insertOne/#mongodb-method-db.collection.insertOne) or [`db.collection.replaceOne()`](https://docs.mongodb.com/v4.4/reference/method/db.collection.replaceOne/#mongodb-method-db.collection.replaceOne) instead. – Serhii Popov Feb 19 '22 at 14:26
38

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.

Aurélien B
  • 4,590
  • 3
  • 34
  • 48
14

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.

Abhi
  • 6,471
  • 6
  • 40
  • 57
11

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.

RoganRicheart
  • 151
  • 1
  • 4
6

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.

Adam Comerford
  • 21,336
  • 4
  • 65
  • 85
3

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.

Bravo
  • 8,589
  • 14
  • 48
  • 85
  • `db.collection.save()` method updates the document if a document with the same _id already exists in the database. When a document with the same _id already exists in the database the save method completely replaces the document with the new document. From the book- Pro MongoDB Development – jack blank Jan 23 '16 at 11:17
1

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

Jagan
  • 63
  • 1
  • 7
1

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

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