Just replyig your first half of the post
Not 100% sure, but I believe they are doing it like that to get user input, which could be done different anyways, as a function myPipeline(skip, limit) could retrieve the full pipeline as an aggregation, etc.
But after all that is converted into a single query, and they are seeing the top-k / coalescence sorting, from the pipeline optimization.
Note that sort + limit are normally merged together, and if there is a skip, is between limit and sort, sort will done also using skip+limit.
{ $sort: { age : -1 } },
{ $skip: 10 },
{ $limit: 5 }
{
"$sort" : {
"sortKey" : {
"age" : -1
},
"limit" : NumberLong(15)
}
},
{
"$skip" : NumberLong(10)
}
With all this said, you may be able to move skip to the first stages such that it occurs before the $lookup…