Skip to content

MongoDB insert if not exists AQSA Spark By {Examples}

  • by

This article on MongoDB will focus on how to insert a document if not exists with four different examples and illustrate how to implement it. Here, the collection student contains only two documents that will be further inserted if any of the specified document is not exists.

#Create Collection
db.student.insertMany([
{
“_id”: 1,
“name”: “Bella steve”,
“age”: 23,
“email”: “bella@gmail.com”
},
{
“_id”: 2,
“name”: “Mac Berk”,
“age”: 20,
“email”: “mac@gmail.com”
}
]
)

If we try to insert the document with the insert method where the document contains the already existing _id value. Then the duplicate error will be generated as shown in the query.

To avoid this kind of errors and insert only if the docuemnt not exists with out returning an error, use the following methods.

1. Using replaceOne() method to insert if not exists in MongoDB

You can use the MongoDB replaceOne() method along with the upsert:true option to insert a document if not exist. The replaceOne() method is used to replace a document in a collection that fits the filter criteria. The upsert performs the combination of the “update” and “insert”, It updates an existing row if a specified value already exists in a collection, and inserts a new document if the specified value doesn’t already exist.

Here, the replaceOne() method replaces a document with the _id value. In contrast, a new document will be added if it does not already exist.

#Usage of replaceOne() method
db.student.replaceOne(
{ _id: 1 },
{ _id: 1, name: “Marrie”, age: 28 },
{ upsert: true }
);

In the above query, as a document with the _id value of 1 already exists. Hence, it replaces it with a new document that has name as Marrie and age as 28. If no document with a _id value of 1 is found, a new document will be inserted with the specified fields.

The { upsert: true } argument specifies this behavior. The output shows that the document already exists, so it is modified in the collection student.

We can see that the _id:1 is updated with the new values to the collection student.

Now, Let’s try to insert a document that doesn’t exists with the same statement.

# Insert a new document
db.student.replaceOne(
{ _id: 3 },
{ _id: 3, name: “Scott”, age: 32 },
{ upsert: true }
);

2. Using findOneAndUpdate() method

Next, the findOneAndUpdate() method is used to update the first matched record with the filter and upsert:true creates a new document if the document doesn’t exists that match the filter .

# Usage of findOneAndUpdate() method
db.student.findOneAndUpdate(
{ email: “kalus@gmail.com” },
{ $setOnInsert: { _id: 3,name: “Klaus” } },
{ upsert: true, returnOriginal: false }
)

The above query will find a document in the student collection with the email value of kalus@gmail.com and updates it with the given fields. The second argument is set with the $setOnInsert operator which is used to set the _id value to 3 and the name value to Klaus only when a new document is inserted.

When no document is identified using the given filter, the upsert option will insert a new document. Here the { returnOriginal: false } method returns the modified document instead of the initial document. The output displayed the new document as if it did not exist.

3. Using updateOne() method

Moreover, we can update a single document in a collection that matches a query by using the updateOne() method, with the upsert option used to insert a new document if none matches the query. Let’s take the following query, which is similar to the aforementioned example, but it uses the updateOne() method instead.

# Usage of updateOne() method
db.student.updateOne(
{ email: “alex@gmail.com” },
{ $setOnInsert: { name: “Alex” } },
{ upsert: true }
)

The aforementioned search modifies or adds a document to the student collection. It finds a document with the “email value of alex@gmail.com and the $setOnInsert operator sets the name value to Alex if a new document is inserted.  

Similarly, If the given filter fails to find any documents, the upsert command with the true value instructs the system to insert a new document. Now, look below to see that the document is upserted as it does not exist in the collection.

We can see the upserted document here as it did not exist before.

4. Using bulkWrite() method to insert if not exists in MongoDB

The MongoDB bulkWrite() method updates or inserts if not exists multiple docuemnts. Here the bulkWrite operations are specified where the updateOne method updates at most one document that matches the given filter criteria.

#Usage of bulkWrite() method
db.student.bulkWrite([
{
updateOne: {
filter: { email: “nina@gmail.com” },
update: { $setOnInsert: { _id: 5, name: “Nina Rich” } },
upsert: true
}
}
])

Yields below output.

We can query the upserted document to see it.

More details about this method can be found here.

5. Conclusion

In conclusion, there are several ways to perform an insert if not exists operation in MongoDB which is discussed in the prior examples. Prety much all examples we have used the upsert property, The upsert performs the combination of the “update” and “insert”, It updates an existing row if a specified value already exists in a collection, and inserts a new document if the specified value doesn’t already exist.

 This article on MongoDB will focus on how to insert a document if not exists with four different examples and illustrate how to implement it. Here, the collection student contains only two documents that will be further inserted if any of the specified document is not exists. #Create Collection db.student.insertMany([ { “_id”: 1, “name”: “Bella  Read More MongoDB 

Leave a Reply

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