node.jsmongodb

MongoDB update multiple rows in a single query


I have a collection with the following document:

{
   "_id" : 1,
   "item" : "item1",
   "stock" : 184
}
{
   "_id" : 2,
   "item" : "item2",
   "stock" : 330
}
{
   "_id" : 3,
   "item" : "item3",
   "stock" : 140
}

I want to update like this:

{
   "_id" : 1,
   "item" : "item1",
   "stock" : 80
}
{
   "_id" : 2,
   "item" : "item2",
   "stock" : 60
}
{
   "_id" : 3,
   "item" : "item3",
   "stock" : 170
}

I can use forEach but updating thousands of records will be time consuming.

How can I update using a single query?


Solution

  • You can use a bulk operation in nodejs via Collection.initializeUnorderedBulkOp

    var bulkOp = yourCollection.initializeUnorderedBulkOp();
    
    bulkOp.find({ _id: 1 }).updateOne({ /* update document */ });
    bulkOp.find({ _id: 2 }).updateOne({ /* update document */ });
    // etc
    
    bulkOp.execute();
    

    You can build it however you need to and then have the database do it all at once.