MongoDB 的插入和更新, $setOnInsert、upsert和$set、upsert


一. 多條數據插入,性能相關.

1. 多條數據插入的時候,如果數據量大,一定要記得給字段添加索引.

2. 可以使用 insert_many,  update_many

 

二. 更新多條數據的時候.( $setOnInsertupsert$setupsert)

$setOnInsert
$setOnInsert指令往往同upsert、$set指令配合使用。mongodb官網說明:

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. If the update operation does not result in an insert, $setOnInsert does nothing.

如果upsert設為true。當滿足查詢條件的記錄存在,則不執行$setOnInsert中的操作,當滿足條件的記錄不存在則執行$setOnInsert操作。

與$set指令配合使用,可以作為$set指令的補充。

當滿足查詢條件的記錄存在,則執行 $set操作,當滿足查詢條件的記錄不存在,則新增一條記錄,其中包含$set指令設置的屬性以及$setOnInsert 指令設置的屬性。

db.getCollection('tt').update(
   {"_id" : ObjectId("5dc2cd255ee0a3a2c2c4c384")},
   {
       "$setOnInsert": { "pon" : "a" },
       "$set": { "a" : "e" }
   },
   { upsert: true }
)

 

當滿足查詢條件{"_id" : ObjectId("5dc2cd255ee0a3a2c2c4c384")}的記錄存在,則只更新或新增其{ "a" : "e" }屬性。如果不存在,將創建一條包含自動生成主鍵的記錄:
{ "_id" : ObjectId("5dc2cd255ee0a3a2c2c4c384"), "a" : "e", "pon" : "a" }

注意:
$setOnInsert和$set中的屬性記錄不能相同

mongo更新語句使用$setOnInsert、upsert和$set、upsert的區別


對於查詢到的記錄。
使用$set、upsert 存在則更新,不存在則新增
使用$setOnInsert、upsert存在則不操作,不存在則新增

 

 



參考博客:https://blog.csdn.net/newCheng/article/details/102943976


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM