MongoDB $sort (aggregation) doesn't working

Viewed 58

I have this aggregation query:

db.getCollection('collectionName').aggregate([

{
    $facet: {
        "myAttrName": [
            {
                $match: {
                    $or: [
                        {
                            "key1": "value1"
                        },
                        {
                            "key2": "value2"
                        }
                    ],
                    status: "OK"
                }
            },
            {
                $skip: 0
            },
            {
                $limit: 10
            },
            {
                $sort: {
                    timestamp: -1
                }
            }
        ]
    }
}



])

Well.. it doesn't sorts the results properly. I just see them ordered by time of adding them "fifo".

When Im just doing regular find (no aggregation) with .sort({timestamp: -1}) it works properly.

What am I missing in here?

1 Answers

The aggregation stages executing in order, in your query $skip and $limit stages executed before the $sort, so sort will apply only in 10 documents,

You can move $sort state before $skip stage.

Playground

Related