[英]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.