Gavin Yap
Gavin Yap

Reputation: 762

Chaining limit() in mongo to avoid return of all result

Would the following query:

db.collection.find() \
.limit(<max no. of item to return>) \
.skip(<(pageIndex-1)*no. of item to display>) \
.limit(<no. of item to display>)

Still performs the first limiter "max no. of item to return" or the second limiter "no. of item to display", will be honored.

E.g. if I have 10,000 records

I would like to cap the maximum pagination at 5,000th records, but display 100 per pager index and the would yield me a 50 pages of results, regardless if the 10,000 records grows.

Upvotes: 1

Views: 33

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

find only supports a single limit, but you can use an aggregation pipeline to do this:

db.collection.aggregate([
    {$limit: n},
    {$skip: (pageIndex-1)*m},
    {$limit: m}
])

However, note that you'll always be reading all n records from the collection, so it's probably better to perform this check in business logic instead.

Upvotes: 2

Related Questions