How to sort a collection by date in MongoDB ?

  • 3 Answer(s)

    Try this below code:

    collection.find().sort({datefield: -1}, function(err, cursor){...});

    In most use cases we wish to have recent datas to be returned (like for latest updates / inserts).

    Answered on January 11, 2019.
    Add Comment

    For the following statement are, 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 using any of the following ways for, you can sort ascending on datefield.

    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) {...});

    The place of the 1, you can also be using ‘ascending‘ or ‘asc

    To using ‘desc‘ for descending, or -1 in place of the 1.

    Answered on January 11, 2019.
    Add Comment

    You can using the following code:

    collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});
    Answered on January 11, 2019.
    Add Comment

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.