MongoDB $setOnInsert Operator (original) (raw)

Last Updated : 12 Jul, 2025

The**$setOnInsert** operator in **MongoDB is a powerful tool used in updating operations with the **upsert**option. It allows us to specify values that should be set only when a new document is inserted. In this article, we will learn about the ****$setOnInsert Operator in MongoDB** in detail and so on.

MongoDB $setOnInsert Operator

**Syntax:

db.collection.update(
,
{ $setOnInsert: { : , : , ... } },
{ upsert: true }
)

Examples of MongoDB $setOnInsert Operator

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.

**Output:

demo database and collection example

Example 1: Upsert Results in an Insert

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": "Mina",
"name.last": "Singh",
"personalDetails.age": 24,
"personalDetails.contactInfo": 345678901
},
{
$setOnInsert: { department: "Development", salary: 45000 }
},
{ upsert: true }
)

**Output:

example 1 output

Example 2: Inserting New Embedded Fields in New Document

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(
{ "name.first": "Vinod", "experienceYear": 5 },
{
$setOnInsert: {
"personalDetails.age": 27,
"personalDetails.contactInfo": 345678901
}
},
{ upsert: true }
)

**Output:

example 2 output

Example 3: Effect of $setOnInsert Operator on Matched Documents

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

**Query:

db.Example.update(
{ "name.first": "Mina" },
{
$setOnInsert: {
"personalDetails.age": 27,
"personalDetails.contactInfo": 345678901
}
},
{ upsert: true }
)

**Before:

before collection

**Output After:

example 3 output

Key Takeaways About $setOnInsert Operator

Conclusion

The $setOnInsert operator in MongoDB provides a way to set specific values during an upsert operation, ensuring that these values are applied only when inserting new documents. This operator enhances the flexibility and functionality of MongoDB's update operations, making it easier to manage data in your collections.