mongoDB – Upserts – insert or update a document
If we use update command the document is updated only if that document record is present in collection.
But if the requirement is that if document is present then we update it otherwise insert it as a new record.
Then we can use upsert command.
Suppose we run an update command as follows
> db.users.update({"name":"mike"},{$set:{$age: 30}} );
If there is a record names “mike” in the user’s collection then it will be updated but if there is no document named “mike” then it will have no effect on it.
So if we want that if document is present then is should be updated else a new document should be add in collection then we have to use “upsert” command.
So if i use a third parameter as upsert: true in the above command then mongoDB will create a new document.
> db.users.update({"name":"mike"},{$set:{$age: 30}, {upsert:true}} );
If we do an update on an empty record the mongoDB will insert a new record.
db.foo.update( { username : 'foo' }, { '$set' : { 'interests': [ 'reading' , 'internet' ] } } , { upsert : true } );
Result: { "_id" : ObjectId("507b78232e8dfde94c149949"), "interests" : [ "reading", "internet" ], "username" : "foo" }