如何根据请求数组更新 MongoDB 多个文档集合中的“order”字段?

huangapple go评论55阅读模式
英文:

How to update "order" field in mongodb multiple documents collection accroding to request array?

问题

我可以帮您翻译代码部分:

我使用这段代码来做这个事情
```javascript
  const update = async (item) => {
                await Service.updateOne({ _id: item._id }, { order: item.order });
            };
            arr.forEach((item) => update(item));

是否可以使用updateMany方法并且只发出一个请求来完成相同的操作?

英文:

I use this code to do this:

  const update = async (item) => {
                await Service.updateOne({ _id: item._id }, { order: item.order });
            };
            arr.forEach((item) => update(item));

can I do the same using updateMany method and making only one request to DB?

答案1

得分: 0

你可以使用 bulkWrite。

例如,我已经映射了一个数据数组,对于每个条目,设置了一个 updateOne 操作,带有 _id 过滤器和更新指令,以将值字段更新为 item.value 的值。

const operations = data.map((item) => ({
   updateOne: {
     filter: { _id: item._id },
     update: { $set: { value: item.value } }
   }
}));

Service.bulkWrite(operations)

这是文档链接:https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/

希望这有所帮助!

英文:

You could use bulkWrite

For this example i have mapped a data array and for each entry set updateOne operation with _id filter and instruction to update the value field with item.value value

const operations = data.map((item) => ({
   updateOne: {
     filter: { _id: item._id },
     update: { $set: { value: item.value } }
   }
}));

Service.bulkWrite(operations)

Here is a link to the documentation: https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/

Hope this helps!

huangapple
  • 本文由 发表于 2023年3月31日 04:54:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定