DEV Community

loading...
Cover image for Bulk updating MongoDb documents

Bulk updating MongoDb documents

Visakh Vijayan
Willing to learn anything and everything exciting. Always awake. Skips food for fun.
Updated on ・1 min read

Just like SQL Mongo also has a bulk update command. It's as simple as -

db.getCollection('<name>').bulkWrite
([
    {
        updateOne:
        {
           filter: {<your-condition>},
           update: {<what-you-want-to-update>
        }
    }
]);
Enter fullscreen mode Exit fullscreen mode

And the updateOne block can be repeated "n" times.

If you are trying to update from an excel file, use the CONCATENATE().

Here is a sample -

=CONCATENATE("{updateOne:{filter:{","'brands.brandId'",":'",E2,"'},update:{$set:{","'brands.$.image'",":'",F2,"'}}}},")
Enter fullscreen mode Exit fullscreen mode

I have values in E2 and F2 columns.
Note: Don't forget the last comma in the CONCATENATE(). Since bulkWrite() accepts an array, it will need the jsons comma separated.

Happy coding :D

Discussion (0)