After put sorting and query its become slow to fetch

i have the model which is a view basically. Here i want the pagination but i did pagination for it but it give me same time for 5 records as it give me for entire collection records 5 seconds. even i have implemented limit still its giving me same time

this is my query

const filterPosts = await Model.aggregate([
        { $match: matchObj },
        { $sort: sortType },
        { $limit: 10 },
      ]);

now if i use limit first then use my match query object it work fast

const filterPosts = await Model.aggregate([
        { $limit: 10 },
        { $match: matchObj },
        { $sort: sortType },
      ]);

kindly help me in that im struck in that since week

Hi @Mehmood_Zubair and welcome to the MongoDB community forum!!

For better understanding of the delay being seen, it would be great, if you could share how would you like the aggregation response to look like.

For instance, the first query you mentioned:

This matches the the condition from the entire collection and then displays the 10 records after the sort operation has been applied.

where on the other hand, the following query

first filters out only 10 documents and then sorts and matches the condition to meet. This explains why the second query is faster as this only processes the first 10 documents of the collection.

Please note that the two queries above are not the same and will not result in the same result set

If possible, please share the same document from the collection for better understanding.

Best Regads
Aasawari

1 Like