Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by date in mongoose aggregation framework

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. The grouping is done on a date excluding time data field like: "2013 02 06". Code looks like this:

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: {
                        year: "$_id.year",
                        month:"$_id.month",
                        day:"$_id.day"
                },
                count: 1,
                _id: 0
            }}
        ], callback);

The grouped results are perfect, except that they are not sorted. Here is an example of output:

[
    {
        count: 1,
        date: {
            year: 2013,
            month: 2,
            day: 7
        }
    },
    {
        count: 1906,
        date: {
            year: 2013,
            month: 2,
            day: 4
        }
    },
    {
        count: 1580,
        date: {
            year: 2013,
            month: 2,
            day: 5
        }
    },
    {
        count: 640,
        date: {
            year: 2013,
            month: 2,
            day: 6
        }
    }
]

I know the sorting is done by adding this: {$sort: val}. But now I'm not sure what should be the val so the results would be sorted by date as my grouping key es an object of 3 values constructing the date. Does anyone know how this could be accomplished?

EDIT Have tryed this and it worked :)

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

like image 576
ArVan Avatar asked Feb 07 '13 08:02

ArVan


People also ask

How do I sort an array in MongoDB aggregation?

To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.

What is sort aggregation?

This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field.


1 Answers

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}}
like image 163
ArVan Avatar answered Sep 24 '22 19:09

ArVan