Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 this collection like this using a single query.

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

I can do it using forEach but I have to update thousands of records at once which will time consuming. So does MongoDB have this functionality?

Your help will be highly appreciated.

like image 965
Saurabh Agrawal Avatar asked Jan 27 '23 07:01

Saurabh Agrawal


1 Answers

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.

like image 136
kmdreko Avatar answered Jan 29 '23 19:01

kmdreko