zoukankan      html  css  js  c++  java
  • Mongodb $setOnInsert操作符 和upsert:true

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

    一. 多条数据插入,性能相关.

    1. 多条数据插入的时候,如果数据量大,一定要记得给字段添加索引.

    2. 可以使用 insert_many, update_many

    二. 更新多条数据的时候.( $setOnInsert、upsert和$set、upsert)

    def save_mongodb(self, item):
      item["updateTime"] = datetime.datetime.now()
      # db_gilt_goods.update({"spuId": item.get("spuId")}, {'$set': dict(item)}, upsert=True)
      db_gilt_goods.update({"spuId": item.get("spuId")}, {'$setOnInsert': dict(item)}, upsert=True)
    

    $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存在则不操作,不存在则新增

  • 相关阅读:
    python计算均值方差
    Linux shell一行流编程实践
    where are you from
    dinner vs supper
    Python格式化输出
    吐槽win8
    HTML学习(六)图像
    HTML学习(五)链接
    HTML学习(四)样式
    URL与String转换
  • 原文地址:https://www.cnblogs.com/gqv2009/p/15044938.html
Copyright © 2011-2022 走看看