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 col
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
.