Sort by date is wrong when using $facet

Lastly I’m using mongodb to build Trivia game, I’m sorting by default all the questions by last added.

I build the next query by my needs:

    db.getCollection("questions").aggregate([{
                    $facet:
                        {
                            "data":[
                                {$match:{}},
                                {$skip:0},
                                {$limit:10},
                                {$sort:{ time_added: 1 }}
                                ],
                            "filterCount":[{$match:{}}, {$group:{_id:null,count:{$sum:1}}}],
                            "totalCount":[{$group:{_id:null,count:{$sum:1}}}]                        
                        }
            }])

Using regular query, to find data I get it order perfect by ‘time_added’, but using this sort, all the data inside ‘data’ is not order well.

Can’t find any more help in the internet.

Here is screenshots

1 Like

:wave: Hi @David_Tayar and welcome to the MongoDB Community forum.

You are limiting your results to the first 10 documents that MongoDB finds and then you are sorting only those 10 documents by time_added. Are you sure that is what you want to do? A limit without any sort before it is not guaranteed to return documents any any particular order.

I think if you do your sort and then limit you might find the results more as you would expect them to be.

1 Like

I change it to:

    {$sort:{ time_added: 1 }}
    {$match:{}},
    {$skip:0},
    {$limit:10},

And it’s work’s like magic !

I was thinking the query go ahead and not step by step.

1 Like

Glad that worked out for you.

One suggestion I would have is to do your match before your sort if you’re planning on filtering documents via the match stage of the pipeline. This will limit the number of documents you need to sort in those cases.

1 Like

It’s the better way, thank you !