R
R
Rag'n' Code Man2021-08-03 17:23:36
Mongoose
Rag'n' Code Man, 2021-08-03 17:23:36

Why do skip and limit in aggregation pipeline work differently than regular find?

I used to paginate with


await this.PupilModel.find().limit(limit).skip(offset) // limit and offset arrive as requset.query

And if I wanted to let's open a third page, given that on one I display 10 elements, I needed to set it limitto 10, and offsetto 20.

But then it was necessary to do filtering and I use MongoDB Aggregation for this purpose.

const result = await this.PupilModel.aggregate(
            this.createFilterPipeline(filters) || [{ $match: {} }]
        )
        .limit(limit)
        .skip(offset);


And now, if I want to open the second page, it limitwill be in the value 10, like offset. I execute the request and get an empty array:
610950e7db361574554294.png

Now, in order for me to open the second page, limitit should be 20, and offset10, and if the third page, then limit= 30, offset= 20

Why is that? Is this a feature of the Aggregation Pipeline or a bug in my code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Romanov, 2021-08-03
@iDmitriyWinX

The aggregation pipeline is executed one by one, first you limit the output limit and you have only 10 records in the output, and then you move the cursor 10 forward and get a void, so in the output after 10 non-records
you need to do this in the aggregation:
either like this :
[
{ "$limit": skip + limit },
{ "$skip": skip }
]
or like this
[
{ "$skip": skip }
{ "$limit": limit },
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question