Incremental / Sequential int IDs with MongoDB using an IdGenerator


I blogged about using incremental ids with mongodb previously, so have a read of that for more information.

Although it’s not ideal, we can use sequential / incremental IDs with MongoDB.
Sometimes (when migrating legacy systems for example) we just can’t get away from using ints for id’s.

While working on implementing MongoDB with N2CMS recently, I came across this very problem.

All IDs are integers, and this can’t be changed
(technically, it could… but I don’t think it’s appropriate… yet)

So, we needed to find a way of generating incremental IDs

Fortunately, the MongoDB driver for .net allows us to write and use our own IdGenerators

So, with that in mind, I’ve created this:

It works on the principal outlined in my previous blog post:
Have a collection that keeps track of collection names, and increment their sequence each time one is inserted

This works well, on single server setups.

I have not yet tested on other setups, but intend to soon.