Search code examples
mongodbspring-datalockingbulkupdate

Does mongodb lock between bulk groups?


Given a collection containing documents of the following format:

{ 
  name:String,
  members: [ { name:String, type: String } ]
}

Let's say I have a mongodb bulk operation, containing two operations:

  • A) for a list of given documents, remove all members with type 'x'
  • B) for that same list of given documents, add a set of members with type 'x'

The question is: will mongodb lock the documents in question between A and B? So that no modification to 'members' of the targeted documents can take place by other processes between A and B?


Solution

  • No it won't. By default, MongoDB operations will be atomic per document, and not within a group of documents (which is what a bulk operation is).

    To quote from the Atomicity and Transactions page:

    In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.

    Also:

    When a single write operation (e.g. db.collection.updateMany()) modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic.

    MongoDB 4.0, however, supports multi-document ACID transactions with some restrictions, such as it supports it only on replica sets, and the overall data in a transaction cannot exceed 16 MB.

    Regarding Spring, MongoDB 4.0 transactions is supported in the Lovelace release (DATAMONGO-1920). There are examples in this blog post by Pivotal.