You read it correct. It is entirely possible and it is simpler than you think.
As many of mongodb people out there will advocate to to prefer to use _id (this is alphanumeric and guaranteed to be unique across machine as well) but software engineers like me find them-self in a situation to use auto increment integers or integer sequence types. One use case of this is to use Numeric Order Id that is auto-increment when ever I insert a new document(row) in collection(table).
So how I was able to solve this problem is below:
The key to note here is the new argument passed to find_and_modify function. Passing new = True returns the modified document and as this is pure mongodb dependent and $inc is said to be thread safe in concurrent environment , this will guarantee to generate unique sequence to passed collection name
In Above code the get_db function just returns me a reference to mongodb connection, which I injected in setting file (Django setting file)
That’s it. You can call next_sequence function with the collection name you want the auto incremented id like below code.
Hope you liked above code.
This code is implemented in python3 using pymongo client library for mongodb. But above code can be ported to other languages as well