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
Written by Adam Chambers
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Mongodb
Authors
dominikgarber
81.15K
sativaware
80.22K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#