Noober
Noober

Reputation: 1626

Sorting on top of grouping in mongodb

I have list of subjects as follows:

[
    { "name": "Algorithms", "category": "Computer Science" },
    { "name": "Android Programming", "category": "Computer Science" },
    { "name": "Polish", "category": "Foreign Languages" },
    { "name": "Portuguese", "category": "Foreign Languages" },
    { "name": "Quechua", "category": "Foreign Languages" },
    { "name": "Health and Medicine", "category": "Science" },
    { "name": "Inorganic Chemistry", "category": "Science" }
]

I am trying to group this based on the category as follows:

[
    {
        "_id": "Computer Science",
        "subjects": [
            {
                "id": "5d2dfd5e349a9a3a48e538ce",
                "name": "Algorithms"
            },
            {
                "id": "5d2dfd5e349a9a3a48e538cf",
                "name": "Android Programming"
            }
        ],
        "count": 2
    },
    {
        "_id": "Foreign Languages",
        "subjects": [
            {
                "id": "5d2dfd5e349a9a3a48e538d0",
                "name": "Polish"
            },
            {
                "id": "5d2dfd5e349a9a3a48e538d1",
                "name": "Portuguese"
            },
            {
                "id": "5d2dfd5e349a9a3a48e538d2",
                "name": "Quechua"
            }
        ],
        "count": 3
    },
    {
        "_id": "Science",
        "subjects": [
            {
                "id": "5d2dfd5e349a9a3a48e538d3",
                "name": "Health and Medicine"
            },
            {
                "id": "5d2dfd5e349a9a3a48e538d4",
                "name": "Inorganic Chemistry"
            }
        ],
        "count": 2
    }
]

I also want the categories to be sorted and subjects to be sorted in each category.

This is what I have done so far:

db.coll.aggregate(
            {
                $group: {
                    _id: "$category",
                    subjects: {
                        $push: {
                            id: "$_id",
                            name: "$name"
                        }
                    },
                    count: { $sum: 1 }
                }

            });

The above works fine in terms of grouping the subjects by categories. But I am not able to do the sorting on top of grouping. I want to sort the categories as well as the subjects in each category.

Upvotes: 1

Views: 25

Answers (1)

mickl
mickl

Reputation: 49985

Run $sort on name before you apply $group and then run next $sort by _id after $group:

db.col.aggregate([
    { $sort: { name: 1 } },
    {
        $group: {
            _id: "$category",
            subjects: {
                $push: {
                    id: "$_id",
                    name: "$name"
                }
            },
            count: { $sum: 1 }
        }
    },
    { $sort: { _id: 1 } }
]);

Mongo Playground

Upvotes: 1

Related Questions