简体   繁体   中英

MongoDB: Update many documents with different data in each

I have an array of _id:

ordersId = ["5ec42446347f396fc3d86a3d", "5ec422d4347f396fc3d86a3c", "5ecefaf0aead3070fbdab7dd"]

And I'm trying to update the documents that match these _ids, but with different data in each of them:

    const existentOrders = await Orders.updateMany(
        { _id: { $in: ordersId } },
        {
            $set: {
                status: "Reviewing",
                cashier: req.id,
                rate: dataBasedOnId,
            },
        }
    );

I have an array of objects that also have these ids:

const ordersRates = [
  {
    _id: "5ec42446347f396fc3d86a3d"
    rate: 2434686948.19
  },
  {
    _id: "5ec422d4347f396fc3d86a3c"
    rate: 2434686948.19
  },
  {
    _id: "5ecefaf0aead3070fbdab7dd",
    rate: 93320.00
  }
]

So what I'm trying to do is to update each document with the rate that is in the ordersRate variable.

Is it possible to update them using only one operation?

Thanks!

I would suggest you to use bulk write which will save network round trip time instead using multiple requests.

You have two variables and form list of UpdateOne operations and pass it to bulk write.

Refer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM