MongoDB

MongoDB $SetOnInsert Operator

The update() method of MongoDB provides several operators to update the values of the document. From these operators, we are going to explore the $setOnInsert operator. The $setOnInsert operator in MongoDB performs an insert and update operation when the upsert flag is applied with the update() function. When the upsert option is specified with the true value and a document is inserted, only the $setOnInsert operator inserts a field during the update operation. The $setOnInsert operator has no impact on the case where the function does not add a document.

How the $SetOnInsert Operator Works in MongoDB

The $setOnInsert operator of MongoDB performs the update() operations that have the upsert flag which implies that this operation only inserts data. To begin the operation of the $setOnInsert operator, we need to create the MongoDB collection. Here, we entitled the collection as “WorkersCollection” and inserted a few documents in this collection. To insert the documents in the “WorkerCollections”, the insertMany query of the MongoDB is deployed which inserts the bulk of the document at the same time. The query of multiple document insertions in “WorkersCollection” is represented in the following:

db.WorkersCollection.insertOne({
        "id" : 1,
        "name" : "Bella",
        "age" : 31,
        "salary" : 50000,
        "height" : 6.5,
        "WorkingHours" :{
                 "Day" : "8hrs",
                 "Night" : "5hrs"
         },
         "Details" : {
                 "City" : "Newyork",
                 "Phone" : "0842888123"
         }
},
{
        "id" : 2,
        "name" : "Kevin",
        "age" : 29,
        "salary" : 45000,
        "height" : 5.9,
        "WorkingHours" :{
                 "Day" : "6hrs",
                 "Night" : "3hrs"
         },
         "Details" : {
                 "City" : "Houston",
                 "Phone" : "8329423099"
         }
},
{
        "id" : 3,
        "name" : "steven",
        "age" : 34,
        "salary" : 39000,
        "height" : 6.4,
        "WorkingHours" :{
                 "Day" : "9hrs",
                 "Night" : "2hrs"
         },
         "Details" : {
                 "City" : "California",
                 "Phone" : "812373002"
         }
 })

When the documents in the provided collection are inserted successfully, the following output is obtained on the MongoDB shell:

{
  acknowledged: true,
  insertedId: ObjectId("63b56a6707e9102dcadcf96a")
}

Example 1: Using the $SetOnInsert Operator to Insert the New Document

We already inserted three documents in the MongoDB collection, “WorkersCollection”. Now, we can add a new document in the same collection with the $setOnInsert operator. We have the following query where we use the update() method to specify the “id”:4” expression. Then, we employ the “$setOnInsert” operator to set the “age” and “salary” fields with the new values that do not exist in the document. After that, we apply the upsert flag with the “true” value. First, the new document is created with the “id”: 4. Then, the $setOnInsert operator assigns the values to the corresponding field of the new document.

db.WorkersCollection.update({"id":4},{ $setOnInsert: {"age":35, "salary": 40000 } },{ upsert: true });

The execution of the previous upsert query returns the output which is shown in the following demonstration. The writeResults has the upsertedCount option which has the value of “1”, indicating that the document is upserted in the collection.

{
  acknowledged: true,
  insertedId: ObjectId("63b56cca378b59e68e0c4608"),
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}

Example 2: Using the $SetOnInsert Operator to Insert the New Embedded Fields in a New Document

The $setOnInsert operator is also used for the embedded document. We can utilize the $setOnInsert operator with the update() function and the upsert option which is assigned to true. Here is a representation of the query to insert the new embedded document in our “WorkersCollection”. We employ the update() method where we set the {“Details.City”: “Chicago”} expression first. Then, we apply the $setOnInsert operator where the embedded fields, “WorkingHours.Day” and “WorkingHours.Night”, are set with new values. The upsert option is also set with the true value to update the embedded document.

db.WorkersCollection.update({"Details.City": "Chicago"},
                  {$setOnInsert: {"WorkingHours.Day": "5hrs" ,"WorkingHours.Night": "5hrs"}},{upsert: true})

The WriteResult in the following output indicates that the upsertedCount is 1 which means that the previous operation is successful.

{
  acknowledged: true,
  insertedId: ObjectId("63b584d4378b59e68e0c4b36"),
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}

Example 3: Using the $setOnInsert Operator to Update the Document

There is another case of the $setOnInsert operator of MongoDB. The prior examples used the $setOnInsert operator to insert the new document. Now, in this instance of MongoDB, we use the $setOnInsert operator to update the document that is already present in the “WorkersCollection” collection. Here, we have an update() query which sets the condition that updates the document whose “id” field value is “2”. When the document is matched, the next operation is accomplished where we use the $set and $setOnInsert operators. The $set operator is specified with the value against the “age” and “height” fields. Then, the $setOnInsert operator is deployed to insert the name field with the “carle” value in the existing document. In the end, we assign the true value to the upsert option to operate.

db.WorkersCollection.update(
  { "id": 2 },
  {
     $set: { age: 40, height: 5.7 },
     $setOnInsert: { name: "carle" }
  },
  { upsert: true }
)

The document is successfully updated, and the following output is shown with the upsertCount option value which is set to true:

{
  acknowledged: true,
  insertedId: 2,
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}

Example 4: Using the $SetOnInsert Operator to Update the Document with No Upsert Operation

Next, we have a case of the $setOnInsert operator where the document is matched and modified but there is no upsert results. We provide the query where we update the document using the update() method. The update() method is further implemented with the operation where the expression is first assigned and the “id” field has the value of “1”. After that, we invoke the $set operator to modify the specified fields and the $setOnInsert operator to set the “name” field with the new value which is “Alex”. The upsert true value is assigned after the $setOnInsert operator.

db.WorkersCollection.update(
  { id: 1 },
  {
     $set: { salary: 60000, height: 4.98 },
     $setOnInsert: { name: "Alex" }
  },
  { upsert: true }
)

We can see that the matchedCount and modifiedCount are set with the value of “1”. The upsertCount has a “zero” value which indicates that the upsert operation is not performed and the “field” name is not updated.

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Example 5: Using the $SetOnInsert Operator for the Matched Document

Next is the operation of the $setOnInsert operator to check whether this operator functions properly with the matching document. The $setOnInsert operator is ineffective with the already existing documents. Let’s have the following query where we have the $setOnInsert operator inside the update() method. The $setOnInsert operator sets the embedded fields, “City” and “Phone”, with the value which is already present in the document. Here, the upsert operation simply ignores the $setOnInsert operator because the specified values are already located in the document.

db.WorkersCollection.update({"name": "Kevin"},
                  {$setOnInsert: {"Details.City": "Houston",
                                  "Details.Phone": "8329423099"}},
                  {upsert: true})

The results just acknowledged the matched document. The upsert operation failed in this case as seen in the following:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 0,
  upsertedCount: 0
}

Conclusion

We demonstrated about the MongoDB $setOnInsert operator. We learned how to use this operator with MongoDB queries. The $SetOnInsert operator is applied within the update() method to upsert the new or specified document. The possible case illustration is provided in this article in which we inserted the new document and the new embedded document with the help of the $setOnInsert operator. After that, we called the $setOnInsert operator to update the already present document and the matched document.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.