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

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.

 

 

If  we do an update on an empty record the mongoDB will insert a new record.

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.