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:
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.