Home:ALL Converter>Mongoose / MongoDB - update multiple documents with different _id and values in one instruction

Mongoose / MongoDB - update multiple documents with different _id and values in one instruction

Ask Time:2022-03-06T23:24:48         Author:Djov

Json Formatter

I am looking for a way to update multiple MongoDB documents in one instruction. I am aware there is a updateMany() query, but it requires a strict filter parameter in order to update multiple documents.

I have an array of objects I'd like to update like so:

const objectsToUpdate = [
    { _id : 1, field : "a" },
    { _id : 2, field : "b" },
    { _id : 3, field : "c" }
]

The array is based on a file I retrieve from an FTP server. I check this file against the database and populate it if there are differences. I could iterate through the array and perform the findOneAndUpdate() query but I have to handle up to 5000 documents in a task.

I am looking for the update counterpart of insertMany() where the documents are looked up by _id and updated in one single query. Is this doable with Mongoose?

Author:Djov,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71371599/mongoose-mongodb-update-multiple-documents-with-different-id-and-values-in
yy