简体   繁体   中英

how can I auto increment a field in mongodb using java code?

I have a comments table with a field "commentId". I created an index on this field. I am not getting how to insert a new document and the commentId field should automatically increment itself upon insertion for every new document. Is there any way I can implement this ?

MongoDB automatically creates an id for every object inserted into it. You don't need to create your own id.

If you do need an incrementing integer id then you run into all sorts of distributed synchronization issues - it's actually quite hard to get right for non-trivial cases.

To generate a unique id the simplest way I can think of:

  • put an index on the id column with a unique constraint.
  • to insert a document query on the index for the highest number, add 1, use that as id.
  • if insert fails due to duplicate index retry

It involves a few round trips but should be robust and with the index in place pretty fast.

If you only have one location writing these you can cash the id in an AtomicInteger locally and only do the full round trip process if you detect a collision then update the AtomicInteger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM