Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use bulkWrite that would be faster than multiple updateOne as there is only one round trip to MongoDB.

const bulkOps = objectsToUpdate.map(obj => {
  return {
    updateOne: {
      filter: {
        _id: obj._id
      },
      // If you were using the MongoDB driver directly, you'd need to do
      // `update: { $set: { field: ... } }` but mongoose adds $set for you
      update: {
        field: obj[field]
      }
    }
  }
})

MongooseModel.bulkWrite(bulkOps).then((res) => {
  console.log("Documents Updated", res.modifiedCount)
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!