【发布时间】:2014-02-16 01:00:18
【问题描述】:
如果存在则如何更新,否则在 javascript/node.js 中插入新文档? 我将作为函数字典的参数,如果字典包含 _id 应该更新,否则在远程服务器上插入(我通过猫鼬与远程服务器连接,并且我有要插入/更新的 Person 模式)。
【问题讨论】:
如果存在则如何更新,否则在 javascript/node.js 中插入新文档? 我将作为函数字典的参数,如果字典包含 _id 应该更新,否则在远程服务器上插入(我通过猫鼬与远程服务器连接,并且我有要插入/更新的 Person 模式)。
【问题讨论】:
collection.update 与 upsert:true。另见here。
【讨论】:
在 Mongoose 中,您将使用 Person.update per the documentation。为了创建一个不存在的文档,您需要在选项哈希中传递{ upsert : true },因为它默认为false。
即
Person.update( { name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback );
【讨论】:
[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); }
【讨论】:
对于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)
【讨论】: