Insert the record if it does not exist in MongoDB
In this article, we briefly discussed about inserting records in MongoDB collection. We also explained different ways to insert these records.
In addition, Upsert and $setOninsert are briefly introduced.
Upsert in MongoDB
Upsert is a MongoDB option for update operations such as update(), findAndModify(), etc. Or, in other words, upsert is the result of combining update and insert (update + insert = upsert).
If the value of this option is true and one or more documents matching the specified query are identified, the update operation will update the matching document or documents. Alternatively, suppose the value of this option is true and no document or documents match the provided document.
In this case, this option creates a new document in the collection with the fields specified in the operation. The upsert operation option value defaults to false.
If the upsert value in the shared collection is true, then you must include the full shared key in the filter.
grammar:
upsert: <boolean>
The upsert option value is true or false.
Now you will understand the use of the upsert option.
Use the findAndModify() method in MongoDB to update and insert
Using findAndModify()
the upsert function, you can use the upsert option. The default value of this option in this method is false.
If you set the value of this option to true, the process will do one of the following.
- The findAndModify() method updates the documents if one or more documents are found matching the given query criteria.
- The findAndModify() method inserts a new document in the collection if no document matches the given query criteria.
grammar:
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>, … ]
})
By adjusting the value of the upsert option to true, you will now insert a new document into the employees collection.
db.employee.findAndModify({query:{name:"Ram"},
update:{$set:{department:"Development"}},
upsert:true})
Here the value of the upsert option is set to true ; findAndModify()
the method inserts a new document containing two fields (name: "Ram" and department: "Development") since no document matches the name Ram.
Upsert uses the update() method in MongoDB
Using update()
the upsert function, you can use the upsert option. The default value of this parameter in this function is false.
If you set the value of this option to true, the process will do one of the following.
- If a document matching the given query is found, the update() method updates the document.
- The update() function adds a new document to the collection if no document satisfies the specified query criteria.
Make a unique index on the name field to prevent MongoDB from adding the same document multiple times. For example, if many documents require the same update with upsert: true, only one update operation will successfully insert the new document with a unique index.
grammar:
db.Collection_name.update({Sele ction_ criteria}, {$set:{Update_data}}, {
upsert: <boo. lean >,
multi: <boo. lean>,
writeConcern: < document>,
collation: < document>,
arrayFilters: [ <filter document1>, … ],
hint: <document|string>
})
By changing the value of the upsert option to true, you will insert a new document into the employees collection.
db.employee.update({name:"Priya"}, {$set: {department: "HR"}},{upsert:true})
Because the value of the upsert option is set to true, the update() function inserts a new document containing two fields (name: "Priya" and department: "HR") because there is no document matching the name Priya.
Using operator expressions to update and insert in MongoDB
Assume that no document in the given collection matches the filter. In this case, the update argument is a document with an update operator.
The value of the upsert option is true; the update operation creates a new document based on the equality clause in the given query parameters and applies the expression in the update parameters.
Or, in other words, when the upsert option is true and no documents match the provided filters, the update operation creates a new document in the given collection with the fields specified in the query and update documents.
example:
By changing the value of the upsert option to true, you will put a new document into the sample collection.
db.example.update({Name: "Rekha"}, // Query parameter
{$set: {Phone: '7842235468 '}, // Update document
$setOnInsert: {Gender: 'Female'}},
{upsert: true})
update()
The function generates a new document containing the query condition field "Name: Rekha" and applies the $set and $setOnInsert operations.
Upsert with Replace Document in MongoDB
Assuming that no document in the provided collection satisfies the filter and the update parameters contain a replacement document, and the value of the upsert document is set to true, the update operation inserts a new document in the collection with the fields specified in the replacement document.
If the replacement document contains _id
a field, MongoDB does not generate a unique _id
field for the new document. Alternatively, if the replacement document lacks _id
a field, MongoDB creates a new _id
field for the new document.
Note that it is not allowed to use different _id
field values in the query parameter and in the replacement document. If you do this, you will run into problems.
example:
By adjusting the value of the upsert option to true, you will now insert a new document into the sample collection.
db.example.update({Name:"Hema"}, // Query parameter
{Name:"Hema", Phone:8332564578}, // Replacement document
{upsert:true})
Upsert using aggregation pipeline in MongoDB
An aggregation pipeline is a multi-stage pipeline that accepts documents as input and produces a result collection of documents.
The resulting document is then taken as input and created in the next step (if available), until the final stage. The number of stages in a pipeline may range from 1 to n.
Assuming that no document matches the specified filter and the update parameters include an aggregation pipeline, and the upsert option is set to true, the update operation will insert a new document into the collection.
This new document is formed using the equality clause in the query parameters, and then the pipeline is applied to it to create the document to be inserted.
example:
By adjusting the value of the upsert option to true, you will now insert a new document into the employees collection.
db.employee.update({name:"Ram"}, [{$set: {department: "HR", age:31}}],{upsert:true})
Querying for upserts using dotted _id in MongoDB
You've seen update()
how the upsert function can change data in a collection based on a query, and how the upsert option can add new fields if no matching documents are found.
_id
However, upserts
with dotted queries are an exception; attempting to insert a document this way will cause MongoDB to error.
explain:
Take a look at the following update operation. The update fails when creating the document to be inserted because the update operation specifies upsert: true and the query uses dot notation to provide a condition on the _id field.
db.employee.update({"_id.name":"Roma", "_id.uid":0},{age:21}, {upsert:true})
So, this article discusses the problem of inserting records with empty fields in MongoDB. Upsert is briefly explained in different scenarios.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
$ne operator in MongoDB
Publish Date:2025/04/11 Views:84 Category:MongoDB
-
This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val
MongoDB $Set Operator
Publish Date:2025/04/11 Views:159 Category:MongoDB
-
With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given
Difference between $push and $addToSet in MongoDB
Publish Date:2025/04/11 Views:63 Category:MongoDB
-
This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato
Sort a collection by date in MongoDB
Publish Date:2025/04/11 Views:64 Category:MongoDB
-
In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB
Counting records in MongoDB
Publish Date:2025/04/11 Views:146 Category:MongoDB
-
This article discusses operators in MongoDB, aggregation operators, and different ways to calculate the total number of records. Operations in MongoDB CRUD operations are a user interface concept that allows users to browse, search, and cha
Pretty printing in MongoDB
Publish Date:2025/04/11 Views:150 Category:MongoDB
-
This article will discuss how to use pretty printing in MongoDB to display formatted results. Pretty printing in MongoDB A cursor is an object that allows programmers in the Mongo world to iterate over documents in a Mongo collection. Altho
MongoDB Adding Elements to an Array
Publish Date:2025/04/11 Views:136 Category:MongoDB
-
This article will cover the various ways to add to an array in MongoDB. Adding to an array in MongoDB Use the $push operator to add values to an array The $push operator is one of the various array update operators provided by MongoDB
MongoDB Search by ID
Publish Date:2025/04/11 Views:131 Category:MongoDB
-
The following article provides an overview of MongoDB find by Id() method. MongoDB provides a find by Id() function which can retrieve documents matching a user id. To use search by Id() in MongoDB, you need to use the find() function. If n
MongoDB starts with a query
Publish Date:2025/04/10 Views:195 Category:MongoDB
-
In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries. MongoDB starts querying using $regex If you want to use $regex , use one of t