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.
The example assumes Mongoose
Basically all we have to do is pass an argument to the sort function indicating the sort column and sort direction. Notice I've also included a limit clause to implement a top n type of query.