Check out myAngular article series with live demos

Sorting by ObjectId in MongoDB

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
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.

The example assumes Mongoose

sort descending

myCollection.find().sort([['_id', -1]]).limit(5).select('title _id').exec(function(e, data){ //handle result } });

sort ascending

myCollection.find().sort([['_id', 1]]).limit(5).select('title _id').exec(function(e, data){ //handle result } });

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.

If you liked this article, it to your friends.

I also invite you to follow me on twitter