180

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?

James M
  • 18,506
  • 3
  • 48
  • 56
flow
  • 4,828
  • 6
  • 26
  • 41
  • 1
    simple , collection.find().sort({datefield: 1}, function(err, cursor){...}); or you can also use collection.find().sort({datefield: -1}, function(err, cursor){...}); – Atul Jain Jan 14 '15 at 08:05
  • Note that you might not need a `date` column: https://stackoverflow.com/questions/5125521/uses-for-mongodb-objectid-creation-time – phil294 Jul 30 '19 at 22:46

10 Answers10

264

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

Sushant Gupta
  • 8,980
  • 5
  • 43
  • 48
  • 1
    What do you intend to put in the function? Just trying to sort on `Date` objects without a function is not working for me on 2.6.3. – Sam Brightman Nov 17 '15 at 11:40
  • @SamBrightman That function is just a callback. Whatever you want to do with the query result, you put that logic inside your callback. You can read more on what callbacks are and how they work to learn event based programming. – Sushant Gupta Nov 17 '15 at 14:20
  • Sure, I know what a callback is. I only saw the sorting requirement in the question and all the answers give callbacks. At the same time, sorting wasn't working for me, so I thought maybe you have to do additional work in the function. – Sam Brightman Nov 17 '15 at 14:25
  • 1
    @SamBrightman Oh ok. For convenience you can be explicit and chain like `collection.find().sort(...).exec(function(err, cursor) {})` – Sushant Gupta Nov 17 '15 at 14:52
  • 5
    it says sort() only takes 1 Argument – Jitendra Pancholi Nov 18 '16 at 07:35
92
db.getCollection('').find({}).sort({_id:-1}) 

This will sort your collection in descending order based on the date of insertion

Rob
  • 26,989
  • 16
  • 82
  • 98
Rich Rajah
  • 2,256
  • 1
  • 12
  • 14
49

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
16

Sushant Gupta's answers are a tad bit outdated and don't work anymore.

The following snippet should be like this now :

collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});

krikara
  • 2,395
  • 10
  • 37
  • 71
  • @JohnnyHK Sweet. I don't remember the exact scenario, but last summer I was trying to get the sort to work with Sushant's snippet and it just wasn't working for me. Perhaps it is because it was lacking the `toArray` part. – krikara Jan 15 '15 at 03:06
  • This is actually a wrong answer, it gives wrong result in node.js – David Aleksanyan Nov 24 '16 at 10:41
12

This worked for me:

collection.find({}, {"sort" : [['datefield', 'asc']]}, function (err, docs) { ... });

Using Node.js, Express.js, and Monk

GoldfishGrenade
  • 621
  • 1
  • 6
  • 14
7
collection.find().sort('date':1).exec(function(err, doc) {});

this worked for me

referred https://docs.mongodb.org/getting-started/node/query/

Naik Ashwini
  • 750
  • 12
  • 32
6

With mongoose it's as simple as:

collection.find().sort('-date').exec(function(err, collectionItems) {
  // here's your code
})
emil.c
  • 1,987
  • 2
  • 26
  • 46
4

Additional Square [ ] Bracket is required for sorting parameter to work.

collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {});
DB Prasad
  • 785
  • 7
  • 9
3

if your date format is like this : 14/02/1989 ----> you may find some problems

you need to use ISOdate like this :

var start_date = new Date(2012, 07, x, x, x); 

-----> the result ------>ISODate("2012-07-14T08:14:00.201Z")

now just use the query like this :

 collection.find( { query : query ,$orderby :{start_date : -1}} ,function (err, cursor) {...}

that's it :)

Aouidane Med Amine
  • 1,571
  • 16
  • 17
2

With mongoose I was not able to use 'toArray', and was getting the error: TypeError: Collection.find(...).sort(...).toArray is not a function. The toArray function exists on the Cursor class from the Native MongoDB NodeJS driver (reference).

Also sort accepts only one parameter, so you can't pass your function inside it.

This worked for me (as answered by Emil):

collection.find().sort('-date').exec(function(error, result) {
  // Your code
})
Pransh Tiwari
  • 3,983
  • 1
  • 32
  • 43