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?
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).
Sorting by date doesn't require anything special. Just sort by the desired date field of the collection.
Updated for the 1.4.28 node.js native driver, you can sort ascending on datefield
using any of the following ways:
collection.find().sort({datefield: 1}).toArray(function(err, docs) {...});
collection.find().sort('datefield', 1).toArray(function(err, docs) {...});
collection.find().sort([['datefield', 1]]).toArray(function(err, docs) {...});
collection.find({}, {sort: {datefield: 1}}).toArray(function(err, docs) {...});
collection.find({}, {sort: [['datefield', 1]]}).toArray(function(err, docs) {...});
'asc'
or 'ascending'
can also be used in place of the 1
.
To sort descending, use 'desc'
, 'descending'
, or -1
in place of the 1
.