byp30g
Last Updated: February 25, 2016
·
3.082K
· 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
ObjectId("505bd76785ebb509fc183733").getTimestamp();

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
db.mycollection.find().sort({id:-1}).limit(10); 

Find out more at mongodb.org
http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs