Creating short, unique object id's in MongoDB

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/


Why not use dylang/shortid?

Install using npm npmjs.com/package/shortid:

npm i shortid

Then require:

const shortid = require('shortid');

In mongoose schema:

    new Schema {
        _id: {
            type: String,
            default: shortid.generate
        }
    }

or just insert directly:

    users.insert({
        _id: shortid.generate()
        name: ...
        email: ...
        });

You could try Mongoid::Token

https://github.com/thetron/mongoid_token

From the docs:

This library is a quick and simple way to generate unique, random tokens for your mongoid documents, in the cases where you can't, or don't want to use slugs, or the default MongoDB IDs.

Mongoid::Token can help turn this:

http://myawesomewebapp.com/video/4dcfbb3c6a4f1d4c4a000012/edit

Into something more like this:

http://myawesomewebapp.com/video/83xQ3r/edit