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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With