Search code examples
mongodbmongoosemongodb-querynosql

MongoDB bulk.update() update same document multiple times


i wonder that if we update same document multiple times in mongo bulk update operation, will it create performance problem? what do you thing?

For example

const bulk = SomeModel.collection.initializeUnorderedBulkOp();
bulk.find({ id: '123' }).update({
          $inc: {
            srcCount: -3,
            totalCount: -3,
          },
        });
bulk.find({ id: '123' }).update({
          $inc: {
            destCount: 3,
            totalCount: 3,
          },
        });
bulk.execute();

result is as expected but i wonder this query does tire mongo?


Solution

  • MongoDB will not care the same document has multiple updates in 1 bulk operation, at the end of the day the bulk operation still resolves the updates one at a time, as each collection has a single writer in charge of inserts/updates. It does not track a "state" so updating the same document 2 times is roughly equivalent to updating 2 different documents.

    The main benefit of using bulk operation is to reduce network overhead.

    It is worth noting that each update can have significant overhead as it can cause an index tree update and taking up precious write reader time. Therefor it's recommended you merge this into a single update.