The Wayback Machine - https://web.archive.org/web/20240706230331/https://www.geeksforgeeks.org/upsert-in-mongodb/
Open In App

Upsert in MongoDB

Last Updated : 11 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In MongoDB, upsert is an option that is used for update operation e.g. update(), findAndModify(), etc. Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents. Or if the value of this option is set to true and no document or documents matches the specified document, then this option inserts a new document in the collection and this new document have the fields that indicate in the operation. By default, the value of the upsert option is false. If the value of upsert in a sharded collection is true then you have to include the full shard key in the filter. 

Syntax:

upsert: <boolean>

The value of upsert option is either true or false.

Now we will learn the usage of the upsert option:

Upsert with findAndModify() method:

We can use upsert option with findAndModify() method. In this method, the default value of this option is false. If we set the value of this option is true, then the method performs one of the following operation:

  • If a document or documents found that matches the given query criteria, then the findAndModify() method updates the document/documents.
  • If no document/documents match the given query criteria, then the findAndModify() method inserts a new document in the collection.

Syntax:

db.Collection_name.findAndModify(

{

    selection_criteria:<document>,

    sort: <document>,

    remove: <boolean>,

    update: <document>,

    new: <boolean>,

    fields: <document>,

    upsert: <boolean>,

    bypassDocumentValidation: <boolean>,

    writeConcern: <document>,

    collation: <document>,

    arrayFilters: [ <filterdocument1>, … ]

})

For example:

In this example we are working with 

Database: gfg

Collection: employee

Database: three documents that contains details of employees

Now we are going to insert a new document in employee collection by setting the value of upsert option to true.

 db.employee.findAndModify({query:{name:"Ram"}, 
                            update:{$set:{department:"Development"}},
                            upsert:true})

Here, no document matches the name “Ram”, so the findAndModify() method inserts a new document that contains two fields(i.e., name: “Ram” and department: “Development”) because the value of the upsert option is set to true.

Upsert with update() method:

We can use upsert option with update() method. In this method, the default value of this option is false. If we set the value of this option is true, then the method performs one of the following operations:

  • If a document or documents found that matches the given query criteria, then the update() method updates the document/documents.
  • If no document/documents match the given query criteria, then the update() method inserts a new document in the collection.

Note: To prevent MongoDB from inserting the same document more than once, create a unique index on the name field. With a unique index, if multiple documents want the same update with upsert: true, only one update operation successfully inserts a new document.

Syntax:

db.Collection_name.update({Selection_criteria}, {$set:{Update_data}}, {

     upsert: <boolean>,

     multi: <boolean>,

     writeConcern: <document>,

     collation: <document>,

     arrayFilters: [ <filterdocument1>, … ],

     hint:  <document|string>        

   })

For example:

In this example, we are working with 

Database: gfg

Collection: employee

Database: three documents that contains details of employees

Now we are going to insert a new document in employee collection by setting the value of upsert option to true.

db.employee.update({name:"Priya"}, {$set: {department: "HR"}},{upsert:true})

Here, no document matches the name “Priya”, so the update() method inserts a new document that contains two fields(i.e., name: “Priya” and department: “HR”) because the value of the upsert option is set to true.

Upsert with Operator Expressions:

If no document matches the filter from the given collection and the update parameter is a document that contains update operators, also the value of upsert option is set to true, then the update operation creates new documents from the equality clauses in the given query parameter and applies the expressions from the update parameter. Or in other words, when the value of upsert option is true and no document matches the given filter, then the update operation inserts a new document in the given collection, and the fields inserted in this new document are the fields that specify in the query and update documents. 

Example:

In this example, we are working with 

Database: gfg

Collection: example

Database: five documents that contains details of students

Now we are going to insert a new document in the example collection by setting the value of the upsert option to true.

db.example.update({Name: "Rekha"},   // Query parameter  
                  {$set: {Phone: '7841235468 '}, // Update document
                   $setOnInsert: {Gender: 'Female'}},
                  {upsert: true})

Here, the update() method creates a new document with field “Name: Rekha” from the query condition and then applies the $set and $setOnInsert operations to this document.

Upsert with Replacement Document:

If no document matches the filter from the given collection and the update parameter contains a replacement document, also the value of upsert document is set to true, the update operation inserts a new document in the collection and the fields inserted in this new document are the fields that specify in the replacement document. Here, if the replacement document contains an _id field then MongoDB does not create a new _id field for the new document. Or if the replacement document does not contain an _id field then MongoDB does create a new _id field for the new document. 

Note: You are not allowed to specify different _id field values in the query parameter and replacement document. If you do, then you will get errors.

Example:

In this example, we are working with 

Database: gfg

Collection: example

Database: four documents that contains details of students

Now we are going to insert a new document in the example collection by setting the value of the upsert option to true.

db.example.update({Name:"Hema"}, // Query parameter
                  {Name:"Hema", Phone:8332564578}, // Replacement document
                  {upsert:true})

Upsert with Aggregation Pipeline:

The aggregation pipeline is a multi-stage pipeline, so in each state, the documents taken as input and produce the resultant set of documents now in the next stage(id available) the resultant documents taken as input and produce output, this process is going on till the last stage. The pipeline can have 1 to n number of stages

If no document matches the given filter and the update parameter contains aggregation pipeline, also the value of upsert option is set to true then update operation inserts a new document in the collection. This new document is created from the equality clause present in the query parameter and after that applies the pipeline to the document to create the document to insert.

Example:

In this example, we are working with 

Database: gfg

Collection: employee

Database: three documents that contains details of employees

Now we are going to insert a new document in the employee collection by setting the value of the upsert option to true.

db.employee.update({name:”Ram”}, [{$set: {department: “HR”, age:30}}],{upsert:true})

Upsert with Dotted _id Query:

Till now, we have studied that the update() method can modify data in the collection based on the query and if any matching document is not found with help of upsert option new field can be added to the collection. But upsert with a dotted _id query is an exception and if you attempt to insert a document in this way MongoDB will show you an error.

Example:

Consider the following update operation. Since the update operation specifies upsert:true and the query specifies conditions on the _id field using dot notation, then the update will result in an error when constructing the document to insert.

db.employee.update({“_id.name”:”Roma”, “_id.uid”:0},{age:20}, {upsert:true})

 



Previous Article
Next Article

Similar Reads

Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
MongoDB: An introduction
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term 'NoSQL' means 'non-relational'. It means that MongoDB isn't based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
5 min read
MongoDB vs MySQL
Differences between MongoDB and MySQL on various parameters are discussed below: What are MongoDB and MySQL? MongoDB MySQL MongoDB is an open-source database developed by MongoDB, Inc. MongoDB stores data in JSON-like documents that can vary in structure. It is a popular NoSQL database. MySQL is a popular open-source relational database management
2 min read
Difference between Oracle and MongoDB
1. Oracle : Oracle is a relational database management system (RDBMS). It was developed by Oracle Corporation in 1980. It is the first database designed for grid computing that provides the most flexible and cost-effective way to manage information and application. It runs on major platforms like Windows, Unix, Linux, and macOS. It is a relational
2 min read
Connecting MongoDB to Jupyter Notebook
MongoDB is one of the most famous NoSql databases. It is an open-source database. The simple meaning of the NoSql database is a non-relational database. i.e., It doesn't include the specific structure of databases such as tables and all like the relational database. So, you can design the schemas without any restrictions. Jupyter Notebook is also a
3 min read
Introduction about Node.js and MongoDB
NoSQL databases are databases that store and retrieve the data that is present in a non-tabular format. Depending on the format of the data stored, NoSQL databases are split into 4 major types: Key-Value Graph database Document-oriented Column family These databases are built to address the shortcomings of traditional RDBMS and provide high perform
4 min read
Article Tags :