【问题标题】:How to update if exists otherwise insert new document?如果存在如何更新,否则插入新文档?
【发布时间】:2014-02-16 01:00:18
【问题描述】:

如果存在则如何更新,否则在 javascript/node.js 中插入新文档? 我将作为函数字典的参数,如果字典包含 _id 应该更新,否则在远程服务器上插入(我通过猫鼬与远程服务器连接,并且我有要插入/更新的 Person 模式)。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    collection.updateupsert:true。另见here

    【讨论】:

    • 常见的答案还是可以有具体例子的。
    【解决方案2】:

    在 Mongoose 中,您将使用 Person.update per the documentation。为了创建一个不存在的文档,您需要在选项哈希中传递{ upsert : true },因为它默认为false

    Person.update( { name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback );
    

    【讨论】:

    • 更新已被弃用。请改用 updateOne、updateMany 或 bulkWrite。
    【解决方案3】:

    [db.collection.replaceOne(filter, replacement, options)]upsert:true

    例如来自here

    try {    db.restaurant.replaceOne(
                { "name" : "Pizza Rat's Pizzaria" },
                { "_id": 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 },
                { upsert: true }    
             ); 
        }
    catch (e){ print(e); }
    

    【讨论】:

      【解决方案4】:

      对于python:

      import pymongo
      
      client = pymongo.MongoClient("mongodb_address")
      db = client.db_name
      collection = db[collection_name]
      
      # update 'data' if 'name' exists otherwise insert new document
      collection.find_one_and_update({"name": some_name},
                                     {"$set": {"data": some_data}},
                                     upsert=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        • 2013-04-19
        • 2016-12-10
        相关资源
        最近更新 更多