Sorting by ObjectId in MongoDB

Published: Tue Mar 17 2015

It's common practice in databases to keep a column or field to indicate when a record or document was created. This is useful for audit purposes, but also for sorting. You can add add your own audit fields, but in MongoDB we get a timestamp for free if we define our primary key as an ObjectId. This is because the 12 byte ObjectId type contains a 4 byte time component.
In this post I will show how to add simple sorting to a Mongoose query based on the timestamp component of ObjectId.