• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:10 mins read
You are currently viewing Upsert in MongoDB Explained with Examples

The update and insert operations in MongoDB are combined to form the upsert operation. It enables us to insert a new document if no corresponding document is identified or alter an existing document if a document exists. A significant feature of MongoDB called upsert makes handling data changes and insertions more straightforward.

Advertisements

Following is a simplified explanation of how an upsert operation works:

  1. The database checks if a document with a specific key (e.g., a unique identifier) already exists in the collection.
  2. If a document with the specified key is found, the database updates that document with the new data provided.
  3. If no document with the specified key is found, the database inserts a new document with the provided key and data.

In MongoDB, you can perform an upsert operation when using methods like updateOne() or updateMany() with the upsert option set to true.

1. Using upsert with the updateOne() method

1.1 Syntax of upsert in MongoDB

The syntax for an updateOne() operation.


# Syntax
db.collection_name.updateOne({selection_criteria},{$set:{key/value to update}},{upsert:true} )

The <selection_criteria> option specifies the criteria for finding the document(s) to update or insert. The matched document(s) will get the changes specified by the <update> option. The <upsert> option enables the upsert behavior by taking the boolean value. Here, the upsert operation is performed for the following collection.

1.2 Using upsert with the updateOne() method

Moreover, we can use the upsert option within the updateOne() method just as follows.


# Usage of updateOne() method
db.student.updateOne({name:"Lucy"}, {$set: {age: 24}},{upsert:true})
  • updateOne() is used to update or insert a document.
  • { name: Lucy } is the filter condition that identifies the document to update or the key for the new document.
  • { $set: { age: 24 } } specifies the update operation. If the document exists, it updates the “age” field to “24.” If the document doesn’t exist, it creates a new one with the specified name and “age” field.
  • { upsert: true } indicates that this is an upsert operation.

As the document doesn’t exist, the upsertedCount below indicates that a new document is upserted into the collection. 

Upsert in MongoDB

There, we can see the newly added document using the upsert option. 

Upsert in MongoDB

1.3 Using upsert with the $setOnInsert method

Further, we can utilize the $setOnInsert operator with upsert functionality in MongoDB same as below.


# Usage of $setOnInsert method
db.student.updateOne({name: "Harry"},     
                  {$set: {cell: '9654785423'}, 
                   $setOnInsert: {gender: 'Male'}},  
                  {upsert: true})  

Moreover, the aforementioned command updates a single document using the updateOne() function. It searches for a document with the name field equal to Harry and first performs the $set operation to set the given value of the cell field. Then perform the $setOnInsert operation to update the gender field and set it to Male, but only if the document is being newly inserted (upserted). Using the upsert option, the command inserts a new document if the filter fails to find a match.

Thus the following output indicates that a new document is upserted within the collection.

Upsert in MongoDB

We can view that particular document below using the find query.

Upsert in MongoDB

2. Using upsert with the findAndModify() method

The findAndModify() method of MongoDB provides the upsert functionality like the way we performed below.


# Usage of findAndModify() method
db.student.findAndModify({query:{name:"Jack"},  
                            update:{$set:{course:"Python"}}, 
                            upsert:true})

The command provided above attempts to find a document in the student collection where the name field is equal to Jack through the query parameter using the findAndModify() method. After that, the update option is set, which defines the modifications to be performed on the found document. Finally, the upsert option is set to true which will create a new document if the search criteria do not match any existing documents.

Hence, no such document in the collection fulfills the criteria, so the upsert option is performed.

Upsert in MongoDB

3. Using upsert with the replaceOne() method

The replaceOne() method is also another option that permits the upsert functionality. The query of the replaceOne() method is defined with the upsert option below.


# replaceOne() method
db.student.replaceOne({name: "Alex"}, 
{name: "Elena", course: "SQL"}, 
{upsert: true})

The command above searches for a document with the name field equal to Alex and replaces it with a new document via the replaceOne() method. The replacement document has the name field set to Elena and the course field set to SQL. In the event that no documents meet the filter, the upsert: true option enables the operation to insert a new document.

The output generated below shows that the document is upserted here with the unique id. 

Upsert in MongoDB

Here, we can see the new document by searching for it.

Upsert in MongoDB

More details about this topic can be found here.

4. Conclusion

In conclusion, we have seen the MongoDB upsert operation via different methods. Upsert operations in MongoDB specifically provide a convenient way to handle both updates and insert operations in a single operation. An upsert operation inserts a new document into a collection if it doesn’t already exist, and if a document with a matching key (usually the document’s unique identifier) exists, it updates the existing document with the new data.