2

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?

6
  • move $sort stage to before $skip stage. Commented Sep 7, 2020 at 7:31
  • It sorts here mongoplayground.net/p/c8dCUoD-C0_ and yes, skip before sort makes little sense. Commented Sep 7, 2020 at 7:34
  • Please write this as an answer I will mark it correct. Commented Sep 7, 2020 at 7:35
  • @AlexBlex maybe the link you have provided handles this behind the scenes Commented Sep 7, 2020 at 7:38
  • It's a particularity of the $facet. In a "classic" pipeline it would have worked well docs.mongodb.com/manual/core/aggregation-pipeline-optimization Commented Sep 7, 2020 at 8:07

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.