Search code examples
node.jsexpressmongoose

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


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?


Solution

  • 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!