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

猜你喜欢

转载自www.cnblogs.com/yuanyongqiang/p/12575344.html