Search code examples
c#mongodbuniqueidentitymongodb-.net-driver

C# - Generate "identity" like Id's with NoSQL (MongoDB)?


I've been using MongoDB with C#, and have been using ObjectIds, then later GUIDs for my Entity Ids. I hate looking at these Id's, I think it's counter intuitive... I'd really like to be able to use integers or longs, like relational DBs Identity column. But I'm having a hard time finding a way to do it. If I use collection max + 1, that will lead to race conditions. I've read about using a Hi-Lo Generator algorithm, but how does that work? What if I have 10 app servers running the same code? Does that mean I have to have 10 hi lo identity ranges per collection?

If someone can point me to a C# algorithm to share that would be great! I've seen RNGCryptoServiceProvider by the way, but that's not guaranteed to be unique, and it's not a sequential int/long Identity. I'd rather use Hi-Lo at that point...

Thanks, Tim


Solution

  • You can write your own id generator and use it. Here you can find how. But ObjectId was designed to be unique across all shards/replica sets. So each shard can generate unique id independently from others. With int id in distributed database you will have many problems.