Sort stage does not sort documents correctly

Hi,
I’m trying to sort documents on multiple fields, “ctype” and “cname”.
As you can see in the attached screen capture, it does not work, I should have:

Axis, MA
Axis, MB
Axis, MC

What is wrong ?
Thanks!

What you probably want to do is

{$sort: {'_id.ctype': 1, 'id.cname': 1}}

After the $group, _id is a nested document and you are trying to sort by 2 fields of that document.

4 Likes

It does not change anything to the result, data are not correctly sorted.

Hi @Helene_ORTIZ can you paste your pipeline here so we can see the full thing? The screenshot has parts cut off. You can copt the text of the pipeline by going into the aggregation and clicking the Export button (the right of Save) and then click on the Copy button in the left hand pane (titled My Pipeline). That way we can see what’s actually going through the pipeline.

As @Massimiliano_Marcon stated it sure looks like you’ve nested the fields under _id and his $sort should work for you.

Hi,
Here is my pipeline:

[{
    $match: {
        $and: [{
                instrument: 94
            },
            {
                timestamp: {
                    $gte: new Date('2020-04-01')
                }
            },
            {
                timestamp: {
                    $lte: new Date('2020-04-25')
                }
            }
        ]
    }
}, {
    $group: {
        _id: {
            ctype: "$ctype",
            cname: "$cname",
            pname: "$pname",
            alias: "$alias"
        }
    }
}, {
    $sort: {
        '_id.ctype': 1,
        'id.cname': 1
    }
}]

Hi Hélène,

The second field in your $sort should be _id.cname to match the output of your previous $group stage.

Regards,
Stennie

1 Like

Oops sorrry for that, I’m a bit distracted!
Thanks a lot for your help

Hi Hélène,

No worries. Sounds like we were able to help you find a solution :slight_smile: .

Regards,
Stennie