MongoDB automatically creates an identifier for each object inserted into it. You do not need to create your own identifier.
If you need a incremental integer identifier, then you are faced with all kinds of distributed synchronization problems - in fact, itβs quite difficult to get the right for non-trivial cases.
To create a unique id, the simplest way I can think of:
- enter an index into the id column with a unique constraint.
- to insert a document request into the index for the largest number, add 1, use this as id.
- if the insert failed due to a repeated attempt to repeat the index
It includes several rounds, but should be reliable and with an in-place index pretty quickly.
If you have only one place recording this data, you can click the identifier in AtomicInteger locally and perform a full round-trip workflow if you detect a collision, and then update AtomicInteger.
Tim b source share