MongoDB

How to use upsert query in MongoDB

The databases are broadly categorized into SQL and NoSQL types. MongoDB falls under the latter category and supports a strong querying language to process data. The upsert query in MongoDB is used to assist the update and replace methods. It creates a new document if the condition is not met by the update/replace methods. Some extended methods of an update are also supported by upsert query, and they include findAndModify, updateOne(), replaceOne().

This article will explain the usage of upsert query from basic to advanced levels. The advanced usage of this query will be explained by applying upsert with several methods.

How upsert query works in MongoDB

The upsert option has the following syntax:

upsert: <Boolean>

The Boolean value may be true/false. By default, the upsert has a false value.

How to use upsert query with the update method

This section explains the upsert query with multiple commands. Let’s exercise the update method first. How does the update work in a condition where the document we want to match does not exist?

The staff collection contains the following documents:

> db.staff.find().pretty()

The below-mentioned command tries to update a document(_id: 3) that does not exist, so the update query will neither upsert nor update any document.

> db.staff.update({_id: 3}, {name: "Alen"})

Now, let’s add an upsert option and set its value to true in the same condition as we explained above. The command mentioned below tries to update a document that matches the name: “Sam” field, but the document does not exist.

It is observed from the output that the number of upserted document values is “1”.

> db.staff.update({name: "Sam"}, {desig: "Team-Lead"}, {upsert: true})

To verify this, let’s check the documents inside “staff” collection by using the following command:

> db.staff.find().pretty()

Note: The pretty() method is used to get the output in a clearer format.

How to use upsert query with updateOne method

The upsert option can be used with the updateOne method to insert a document if the condition match is unsuccessful. The “staff” collection contains three documents, and we want to add a document with (_id: 3) that does not exist. To make upsert functional, you must set its value to true, the above scenario is executed by issuing the command mentioned below:

> db.staff.updateOne({_id:3}, {$set: {name: "Sam", desig: "Team-Lead"}}, {upsert: true})

In the above command, we have used “_id: 3” to match a document therefore, the upserted document has been assigned a unique id “_id: 3“. Moreover, you can verify the upsert action by getting the content of staff collection:

> db.staff.find().pretty()

How to use upsert query with replaceOne method

The replaceOne method replaces the field value(s) if the match is successful. And if the matching is not successful, then upsert can be used to add a new document.

In the below stated command, replaceOne command tries to replace the document that has field “name: Tom“(which does not exist actually). The upsert value is “true“, so it will add new document with a default unique id that contains field “name: Jobes” and “desig: Author“:

> db.staff.replaceOne({name: "Tom"}, {name: "Jobes", desig: "Author"}, {upsert: true})

How to use upsert with findAndModify method

The findAndModify() modifies the document and acts almost the same as the update() method, but findAndModify() modifies only one document that matches first, whereas the update() method updates all the matching documents.

The command written below shows the usage of the uspert with the findAndModify() method. As the findAndModify() fails to match any document, therefore a new document comes in:

The “query” keyword used in command tries to match “_id: 5” and tries to upgrade the “num” field by value “15“:

> db.staff.findAndModify({query: {_id: 5}, update: {$inc: {num: 15}}, upsert: true})

The query returns “null” because we have not used sort in the command and also no document matches as well. However, if you look at the content of the “staff” collection, you will find the newly upserted document with id value “_id: 5“:

> db.staff.find().pretty()

Conclusion

MongoDB has a long list of commands and queries to update or replace data inside documents of a collection. Alongside these commands, the upsert query assists these update/replace commands to insert a new document if the update/replace commands fail to match any document. In this guide of the MongoDB series, we have provided the usage of an upsert query with several commands in MongoDB. After analyzing the upsert working mechanism, it is concluded that upsert acts as an insert method for several update/remove methods in MongoDB.

About the author

Adnan Shabbir