0

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?

dstibbe
  • 1,589
  • 18
  • 33
  • 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). What you're describing is a feature of transactions, which is a new MongoDB 4.0 feature. I'm not sure if Spring supports this yet. – kevinadi Jun 17 '19 at 05:57
  • Why mention this as a comment? It is a clear answer.... – dstibbe Jun 18 '19 at 11:17
  • Sure I can put it up as an answer. – kevinadi Jun 18 '19 at 21:48
  • Thx. That is the whole point of SO :P – dstibbe Jun 19 '19 at 10:20

1 Answers1

1

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.

kevinadi
  • 13,365
  • 3
  • 33
  • 49