如果存在则如何更新否则在javascript/node.js中插入新文档?我得到函数字典的参数,如果字典包含_id应该更新,否则在远程服务器上插入(我通过mongoose与远程服务器连接,我有要插入/更新的Person模式).
Emp*_*nal 47
在Mongoose中,您可以Person.update 根据文档使用它.为了创建文档(如果它尚不存在),您需要传入{ upsert : true }默认的选项哈希false.
即
Person.update( { name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback );
Run Code Online (Sandbox Code Playgroud)
[db.collection.replaceOne(filter, replacement, options)] 同 upsert:true
例如从这里:
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); }
Run Code Online (Sandbox Code Playgroud)
对于蟒蛇:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42627 次 |
| 最近记录: |