Last Updated: February 25, 2016
· chambaz

Optimizing Mongo Object Ids

Mongo BSON Object Ids are pretty powerful, here's a few things I wasn't aware you could do with them.

Custom _id type
_id's can be any type, so if your objects have a natural unique identifier, consider using that in _id to both save space and avoid an additional index.

// insert product with custom integer id
db.products.insert({_id:17618, title:'Some Product'});

Free creation timestamp
The BSON ObjectId format provides documents with a creation timestamp (one second granularity) for free!

// will return the time the ObjectId was created

Sort by creation time
BSON ObjectId's begin with a timestamp. Thus sorting by _id, when using the ObjectID type, results in sorting by time.

// get 10 newest items

Find out more at