[英]how to complete (update) a mongoDB document
我面临以下情况:
我有一个服务的 api 请求,该服务在一个集合中创建多个 mongo 文档,例如:
[
{_id: 1, test1: 2, test: 3},
{_id: 2, test1: 3, test: 4}
]
在此之后,第二个服务读取这些文档并搜索信息的另一部分,所以我正在构建一个对象,如:
[
{_id: 1, newValue: 4},
{_id: 2, newValue: 4}
]
我的问题是:我可以使用“_id”值一次更新所有文档吗? 问题是我不想每个文件都更新一个,因为有很多文件,所以我猜最好删除所有这些文件并插入所有信息,你怎么看?
大规模删除然后“重新插入”有点笨拙,也会对索引管理造成影响。 使用bulkWrite
批量进行多次更新是更好的方法:
var bulkOps = [];
for each thing you need to process {
set up _id and newValue ... ;
bulkOps.push({
"updateOne": {
"filter": { "_id": theOneYouAreWorkingOn },
update: { $set: {"newValue": theTargetValue } }
}
});
});
// Send a single big bundle of updates. This could also be wrapped in a transaction:
printjson( db.foo.bulkWrite(bulkOps) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.