How to sort a collection by date in MongoDB?

后端 未结 10 2018
失恋的感觉
失恋的感觉 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条回答
  •  -上瘾入骨i
    2020-12-07 14:52

    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.

提交回复
热议问题