How can I automatically increment a field in mongodb using java code?

I have a comment table with a commentId field. I created an index in this field. I don’t understand how to insert a new document, and the commentId field should automatically increase on insert for each new document. Is there any way to implement this?

+1
source share
1 answer

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.

0
source

All Articles