當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


MongoDB $setOnInsert用法及代碼示例

MongoDB 提供了不同類型的字段更新運算符來更新文檔字段的值,$setOnInsert 運算符就是其中之一。當通過將 upsert 字段的值設置為 true 來在更新操作的幫助下插入新文檔時使用此運算符,然後$setOneInsert運算符將指定的值分配給文檔中的字段。如果更新操作不會用於插入新文檔,則$setOnInsert操作符不會做任何事情。

$setOnInsert 運算符還可以處理嵌入/嵌套文檔。您可以根據需要在 update()、findAndModify() 等方法中使用此運算符。如果使用 upsert:true 的 update() 或 findAndModify() 方法找到了匹配的文檔,那麽 mongoDB 將忽略 $setOnInsert 並應用 $set 運算符,如下例 3 所示。

用法:

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

借助點符號指定嵌入/嵌套文檔中的字段。

在以下示例中,我們正在使用:



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

使用在新文檔中插入新字段$setOnInsert

在這個例子中,我們在 update() 方法的幫助下在 Example 集合中創建一個新文檔,方法是將 upsert 字段的值設置為 true 並使用 $setOneInsert 運算符將值分配給文檔中的部門和工資字段。


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

使用在新文檔中插入新的嵌入字段$setOnInsert

在這個例子中,我們在 update() 方法的幫助下在 Example 集合中創建一個新文檔,方法是將 upsert 字段的值設置為 true 並使用$setOneInsert 運算符將值分配給嵌入的字段,即在文檔中。


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

效果 $setOnInsert 匹配文檔上的運算符:

在這個例子中,我們正在檢查 $setOnInsert 操作符是否與匹配的文檔一起工作。此 $setOnInsert 運算符不適用於已存在的文檔。或者換句話說,當 update() 方法找到匹配的文檔時,MongoDB 將忽略此運算符。


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

前:

後:




相關用法


注:本文由純淨天空篩選整理自ankita_saini大神的英文原創作品 MongoDB – SetOnInsert Operator ($setOnInsert)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。