MongoDB - Оператор SetOnInsert ($ setOnInsert)

Опубликовано: 22 Марта, 2022

MongoDB provides different types of field update operators to update the values of the fields of the documents and $setOnInsert operator is one of them. This operator is used when a new document is inserted with the help of update operation by setting the value of an upsert field to true, then $setOneInsert operator assigns the specified value to the fields in the document. If the update operation will not used to insert new document, then $setOnInsert operator will not do anything.

Оператор $ setOnInsert также может работать со встроенными / вложенными документами. Вы можете использовать этот оператор в таких методах, как update (), findAndModify () и т. Д., В соответствии с вашими требованиями. Если метод update () или findAndModify () с upsert: true нашел соответствующий документ, то mongoDB проигнорирует $ setOnInsert и применит оператор $ set, как показано ниже в примере 3.

Синтаксис:

 db.collection.update (
   <запрос>,
   {$ setOnInsert: {<field1>: <value1>, <field1>: <value2>, ...}},
   {upsert: правда}
)

Указать поле во встроенных / вложенных документах с помощью точечной записи.

В следующих примерах мы работаем с:

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

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.

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

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.

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

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. Or in other words, MongoDB will ignore this operator when the update() method found the matched document.

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

До:

После: