In MongoDB how to create Registration number ?
I need auto incrementing value but MongoDB doesn’t have auto increment by default (risk in case concurrency failure),
so how to do it?
Eg. current registration no : 1
now when I insert a new record this must be 1 + 1 = 2
3
Answers
There is no built in way to achieve this, there are a few solutions for certain situations.
For example if you’re using Mongo Realm you can define a DB trigger, I recommend following this guide
If you’re using
mongoose
in your app there are certain plugins like mongoose-auto-increment that do it for you.The way they work is by creating an additional collection that contains a counter to be used for every insert, however this is not perfect as it your db is still vulnerable to manual updates and human error. This is still the only viable solution that doesn’t require preprocessing of some sort, I recommend to also create a unique index on that field to at least guarantee uniqueness.
I do it like that
FindOneAndUpdate is atomic
Find full example here
https://github.com/iso8859/learn-mongodb-by-example/blob/main/dotnet/02%20-%20Intermediate/InsertLongId.cs
If you need to avoid gaps, you can use the following approach that involves only updates to a single document that are atomic:
First, you pre-fill the invoice collection with a reasonable amount of documents (if you expect 1000 invoices per day, you could create the documents for a year in advance) that has a unique, increasing and gap-less number, e.g.
There should be a unique index on
InvoiceId
and for efficient querying/sorting during the updates another one onHasInvoice
andInvoiceId
. You’d need to insert new documents if you are about to run out of prepared documents.When creating an invoice, you perform a
FindOneAndModify
operation that gets the document with the lowestInvoiceId
that does not have anInvoice
yet. Using the updates, you assign theInvoice
, e.g.:FindOneAndModify
returns the updated document so that you can access the assigned invoice id afterwards.Due to the atomic execution of
FindAndModify
there is no need for transactions; gaps are not possible as always the lowestInvoiceId
is found.