我有要保存的数据列表,如果已经存在,请更新。
我可以使用循环来做到这一点。但是是否有像insertMany
这样的其他方式仅支持插入,但我也想大量插入和更新。
答案 0 :(得分:0)
将updateMany与选项{upsert:true}一起使用,如果文件已经存在,则会对其进行更新,否则请插入新文件。
找到以下带有餐厅集合的示例
{ "_id" : 1, "name" : "Central Perk Cafe", "violations" : 3 }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "violations" : 2 }
{ "_id" : 3, "name" : "Empire State Sub", "violations" : 5 }
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "violations" : 8 }
下面的查询会更新违规等于4的文档,如果文档不存在,请插入新文档。
db.restaurant.updateMany(
{ violations: 4 },
{ $set: { "name" : "Eat and Treat" } },
{ upsert: true }
);
在此处查找更多详细信息:
https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/
答案 1 :(得分:0)
您可以使用Mongo驱动程序提供的批量更新功能。您可以将它们添加到批量交易中并批量执行,而不是循环调用交易。
首先,您需要初始化批量操作,有序/无序:
<input type="text" pattern="^\d{4}[A-Z]{2}$">
或
var bulk = db.collection.initializeUnorderedBulkOp();
然后,您可以继续将事务添加到批量对象中。
var bulk = db.collection.initializeOrderedBulkOp();
或
bulk.insert( {
// attributes
} ); // insert operation
最后您需要致电
bulk.find( {
// query attributes
} ).update( {
$set: {
// set attributes
} } ); // update operation
我不知道这是否可以达到您的目的。
请参考此链接: