mongodb 如果存在,如何更新否则插入新文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21342747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:34:23  来源:igfitidea点击:

How to update if exists otherwise insert new document?

mongodbmongoose

提问by PaolaJ.

How to update if exists otherwise insert new document in javascript/node.js? I am getting as parameter to function dictionary,if dictionary contains _id should update, otherwise insert on remote server (I have connection with remote server through mongoose and I have Person schema which I want to insert/update).

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

回答by EmptyArsenal

In Mongoose, you'd use Person.updateper the documentation. In order to create a document if it doesn't already exist, you need to pass { upsert : true }in the options hash as it defaults to false.

在 Mongoose 中,您将Person.update根据文档使用。如果文档不存在,为了创建文档,您需要传入{ upsert : true }选项哈希,因为它默认为false.

i.e.

IE

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

回答by heinob

collection.updatewith upsert:true. See also here.

collection.updateupsert:true. 另请参见此处

回答by Hrushikesh Dhumal

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

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

E.g. from 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); }

回答by banderlog013

For 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)