DEV Community

Cover image for Bulk updating MongoDb documents
Visakh Vijayan
Visakh Vijayan

Posted on • Edited on

2

Bulk updating MongoDb documents

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

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more