I need to create an auto incremental id field in an envirironment with high concurrency
How to implement an auto incremental id in an environment of 100 isertions per minute?
Hello @jose_cabrera ,
Welcome to The MongoDB Community Forums!
To understand your scenario better, could you please explain your use-case for an auto increment field?
MongoDB provides an _id field for every document which is automatically generated by default. This field is designed to be unique and may be able to be used instead of an auto incremental id field.
If you need an auto incremental id field, you can use a sequence collection to generate unique ids. The sequence collection contains a document that stores the current value of the sequence. Whenever a new document is inserted, the application fetches the next value from the sequence collection and assigns it as the _id of the new document.
To ensure that the sequence is incremented atomically, you can use the findAndModify command with the $inc operator to increment the sequence value and return the updated value in a single atomic operation. This will prevent race conditions that may occur when multiple threads try to increment the sequence at the same time.
Note: A single counter document could be a bottleneck in your application as it has it’s limitations, kindly refer Generating Globally Unique Identifiers for Use with MongoDB | MongoDB Blog
Please refer below blogs to learn more about implementations and working of this.
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.