Suppose I have 10 million documents. I need to skip the last 5 documents and get the last 10 documents.
This code works fast
documents.find({user: 'demo'}).sort({ _id: -1 }).skip(5).limit(10)
This code works very very slowly and loads the system heavily.
documents.aggregate([
{ $match: { user: 'demo' } },
{ $sort: { _id: -1 } },
{ $skip: 5 },
{ $limit: 10 },
])
This will work quickly if the match is moved to the end, but then the results will be incorrect. Help me figure out how to write a query correctly using aggregate