Mongodb Upsert Operation

Let us see the syntax of update query once again.

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

We have seen about <query> and <update> parts in previous article. Let us try to understand what upsert means.

This is directory from official documentation.

If upsert is true and no document matches the query criteria, update() inserts a singledocument. The update creates the new document with either:

  • The fields and values of the <update> parameter if the <update> parameter contains only field and value pairs, or
  • The fields and values of both the <query> and <update> parameters if the <update> parameter contains update operator expressions. The update creates a base document from the equality clauses in the <query> parameter, and then applies the update expressions from the <update>parameter.

If upsert is true and there are documents that match the query criteria, update() performs an update.

Let us try to know this with an example.Currently there are not documents in db. Run below mongodb upsert operation

No documents matched the criteria so nMatched=0
one document is inserted so nUpSerted=1
No documents is modified so nModified=0
now retrieve all documents using db.employees.find().pretty();

MS DOS

1
{ "_id" : ObjectId("559e78ecb3c8ea7523d98767"), "salary" : 100000 }

In this operation, only the fields in <update> part of query are inserted in database and not from <query>. This adheres to first bullet point in documentation.

Now let us write a query that does not match any criteria, update some fields using update operations like $set and do mongodb upsert operation for it.