How to sort a collection by date in MongoDB?

后端 未结 10 2017
失恋的感觉
失恋的感觉 2020-12-07 14:27

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

相关标签:
10条回答
  • 2020-12-07 14:55

    With mongoose it's as simple as:

    collection.find().sort('-date').exec(function(err, collectionItems) {
      // here's your code
    })
    
    0 讨论(0)
  • 2020-12-07 15:00
    collection.find().sort('date':1).exec(function(err, doc) {});
    

    this worked for me

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

    0 讨论(0)
  • 2020-12-07 15:09

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

    0 讨论(0)
  • 2020-12-07 15:10

    This worked for me:

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

    Using Node.js, Express.js, and Monk

    0 讨论(0)
提交回复
热议问题