Sort by date in mongoose aggregation framework Sort by date in mongoose aggregation framework mongoose mongoose

Sort by date in mongoose aggregation framework


It appears that this question has a very simple answer :) Just need to sort by multiple nesteed columns like this:

{$sort: {"date.year":1, "date.month":1, "date.day":1}}


I got stuck with the same problem, thanks for your answer.But I found out that you can get the same result with less code

MyModel.aggregate([            {$match: {$and: [{created_date: {$gte: start_date}}, {created_date: {$lte: end_date}}]}},            {$group: {                _id: {                    year: {$year: "$created_at"},                    month: {$month: "$created_at"},                    day: {$dayOfMonth: "$created_at"}                },                count: {$sum: 1}            }},            {$project: {                date: "$_id", // so this is the shorter way                count: 1,                _id: 0            }},            {$sort: {"date": 1} } // and this will sort based on your date        ], callback);


This would work if you are only sorting by date if you had other columsn to sort on. YOu would need to expand _id