How to sort a collection by date in MongoDB?

flow picture flow · Dec 12, 2012 · Viewed 215.2k times · Source

I am using MongoDB with Node.JS. I have a collection which contains a date and other rows. The date is a JavaScript Date object.

How can I sort this collection by date?

Answer

Sushant Gupta picture Sushant Gupta · Dec 12, 2012

Just a slight modification to @JohnnyHK answer

collection.find().sort({datefield: -1}, function(err, cursor){...});

In many use cases we wish to have latest records to be returned (like for latest updates / inserts).