If I define an unique index on a field (say “field1”) and multiple truly parallel threads (i.e. exact same time up to milliseconds) tries to insert the same <field1: same-value> in the same collection, is it guaranteed that only ONE of these threads will actually succeed and others will fail with “Duplicate Key Error”?
Does the server-side ensure this?
How does the behavior change based on if the field is scalar or array?
We are using java, spring-boot stack to integrate with MongoDB 4.x.
NOTE - Posting on an Urgency. It will be really helpful, if we can receive a kind response soon.
Each insert or update to a single document is atomic in MongoDB and therefore each one takes an exclusive lock on the index and collection documents.
Read more here:
So only a single concurrent thread will be able to set the value whithin a single replica set Primary. (Sharding must have the unique index as the shard key to enforce uniqueness).