Sort by date in mongoose aggregation framework

后端 未结 3 1643
Happy的楠姐
Happy的楠姐 2021-02-13 21:57

Im working on a nodejs+mongodb project using mongoose. Now I have come across a question I don\'t know the answer to. I am using aggregation framework to get grouped results. T

3条回答
  •  孤城傲影
    2021-02-13 22:14

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

提交回复
热议问题