MongoDB uses save and insert option for adding new records in the database. Let me explain the difference between two :
Insert : insert is used to add a document in a mongodb collection
Save : save is used to add as well as update a document in a mongodb collection. It can accept ID field for updation but insert can’t do it. Let me show you by an example :
mongo use school; // It doesn't exist and will be created on the fly switched to db school db.student.insert({name:'Neeraj Bhatt', age:'28'}) WriteResult({ "nInserted" : 1 }) db.student.find(); { "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28" }
You can also pass an ID with insert and it’s whole purpose is to make an unique entry in the collection. Here is an example :
db.student.insert({_id:'537da62', name:'Prashant Gupta', age:'25'}) // You can't use id in place of _id. WriteResult({ "nInserted" : 1 }) db.student.find(); { "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28" } { "_id" : "537da62", "name" : "Prashant Gupta", "age" : "25" }
Now we will use save to add a record :
db.student.save({name:'Vivek Yadav', age:'26'}) WriteResult({ "nInserted" : 1 }) db.student.find(); { "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Neeraj Bhatt", "age" : "28" } { "_id" : "537da62", "name" : "Prashant Gupta", "age" : "25" } { "_id" : ObjectId("537da62d770359c2fb4668e2"), "name" : "Vivek Yadav", "age" : "26" }
Now let us look at the real difference. We can also pass an id with save and it will return us an updated object with values provided :
db.student.save({id: ObjectId('537da62d770359c2fb4668e2'), name:'Vivek Yadav', age:'25'}) // If you are wondering why did i use ObjectId instead of just value of id then please try it yourself. If you just pass id : '537da62d770359c2fb4668e2' then it will add a new record and won't update anything. WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Recent Comments