Open In App

MongoDB – $setOnInsert Operator

MongoDB $setOnInsert Operator is a type of field update operator. The $setOnInsert operator is used in MongoDB update operations with the upsert option. When a new document is inserted, it assigns specified values to the fields in the document. This operator only acts during the insertion of a new document.

This operator can also work with embedded/nested documents. You can use this operator in methods like update(), findAndModify(), etc., according to your requirements.



If the update() or findAndModify() method with upsert: true has found a matching document, then MongoDB will ignore $setOnInsert and apply the $set operator.

Syntax

db.collection.update(
<query>,
{ $setOnInsert: { <field1>: <value1>, <field1>: <value2>, ... } },
{ upsert: true }
)

MongoDB $setOnInsert Operator Example

In these examples, we will work with:



Database: GeeksforGeeks

Collection: Example

Document: one documents that contain the details of the employees in the form of field-value pairs.

Example 1: Inserting new fields in new documents using $setOnInsert

In this example, we are creating a new document in the Example collection with the help of update() method by setting the value of an upsert field to true and using $setOneInsert operator assign the values to the department and salary fields in the document.

Query:

db.Example.update({name: {first: &quot;Mina&quot;, last: &quot;Singh&quot;},
... personalDetails: {age: 24, contactInfo: 345678901}},
... { $setOnInsert: {department: &quot;Development&quot;, salary: 45000}},
... {upsert: true}
... )

Output:

Example 2: Inserting new embedded fields in new document using $setOnInsert

In this example, we are creating a new document in the Example collection with the help of update() method by setting the value of an upsert field to true and using $setOneInsert operator assign the values to embedded fields i.e., in the document.

Query:

db.Example.update({&quot;name.first&quot;: &quot;Vinod&quot;, expreienceYear: 5}, 
{$setOnInsert: {&quot;personalDetails.age&quot;: 27,
&quot;personalDetails.contactInfo&quot;: 345678901}},
{upsert: true})

Output:

Example 3: Effect of $setOnInsert operator on Matched documents

In this example, we are checking if $setOnInsert operator work with matched document or not. This $setOnInsert operator does not work with already present documents.

Query:

db.Example.update({&quot;name.first&quot;: &quot;Mina&quot;}, 
{$setOnInsert: {&quot;personalDetails.age&quot;: 27,
&quot;personalDetails.contactInfo&quot;: 345678001}},
{upsert: true})

Before:

Output After:

Key Takeaways About $setOnInsert Operator

Article Tags :