Creating short, unique object id's in MongoDB

John picture John · May 11, 2011 · Viewed 21.8k times · Source

I'm making an app similar to instagram using Rails/Mongoid. I want a unique ID that I can use in a url like http://instagr.am/p/DJmU8/

What's the easiest way to do that? Can I derive such an ID from the default BSON ObjectID Mongo creates?

Answer

aav picture aav · May 11, 2011

You may try to use first 4 bytes of ObjectID (they will represent timestamp).

But, to be 100% safe, it's better to produce really unique short id, by implementing a counter. You can use separate collection to maintain current value of your counter.

More details on mongo's ObjectID structure can be found here: http://www.mongodb.org/display/DOCS/Object+IDs

As an alternative you can convert convert hex string id representation to a representation based on 36 symbols (26 latin letters + 10 digits). It will obviously be shorter.

It seems, that there is a ruby library, that can do such conversions http://rubyworks.github.com/radix/