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
How to update if exists otherwise insert new document?
提问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.update
per 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 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)