MongoDB does not offer an auto-incementing sequence solution natively. Instead most app developers will come up with their own. So I did!

Imagine you’re building an order system. After processing each order you want to show a number to the customer that they can hold on to and use as reference when contacting customer service.

The idea is to create a sequence collection in Mongo containing a key and a counter:

In this schema key is the name of the collection that the sequence is for and counter holds the next number in the sequence. Once you have the sequence collection you can atomically increment it for each use giving you an pseudo-auto-increment sequence. Using Mongo’s findAndModify you can provide a query that will look up the sequence for “orders” and ask Morphia to increment the counter .

Now you can use this in your order processing code to generate an auto-incrementing number which you then save to the order.

The sequence collection could be used to store auto-incrementing sequences for other collections as well.

Hope that for your next sequencing use-case you can leverage something like this. If you have other ideas, do tell!