Creating unique IDs with NoSQL

I wanted to have unique user friendly IDs for an application I'm working on. No long, hard to type in customer reference numbers. And using MongoDB I didn't have that nifty autoincrementing sql.

The way I solved it was using MongoDBs update command. That command takes an atomic modifier $inc. So you'll need to create a c collection with one document, and increase a value on that counter. Then I'll base64 encode the value to have a slightly more user friendly value. Especially when the sequence grows in size. This is all using Python.

Creating my document:

db.counter.insert({'count': 0})

And here's my unique id generator:

def unique_id():
    db = get_database()
    val = db.command('findandmodify', 'counter', update={'$inc': {'count':1}})['value']['count']
    b = base64.b64encode(str(val))
    result = b.replace('=', '')
    return result

You'll now end up with IDs looking like this:

Be Sociable, Share!

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

Comments are closed.