• 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

  • 相关阅读:
    面试题:1000!结果中有多少个0
    进程和线程的理解
    面试题:栈内存的多线程
    android中activity和service是否在同一个进程中
    面试题:栈排序
    面试题:递归反转一个栈
    面试题:栈的push和pop序列是否一致
    验证码发送到手机上 购买服务器进行发送短信;阿里云/ 腾讯云
    (十一)腾讯云短信使用
    (十)微信小程序---上传图片chooseImage 与 上传到服务器
  • 原文地址:https://www.cnblogs.com/yuanyongqiang/p/12575344.html
Copyright © 2020-2023  润新知