Pagination: How to know if there are more documents in a mongoDB collection?

How can I know if there’re more documents in mongo query that implements limit()

Following the example shared in a post on stack overflow , I somehow still end up getting a false flag but I am sure there’s a next page.

  let pagelimit = number || 10
  const items = db.find({}).sort({ _id: 1 }).limit(pagelimit).toArray()
 
  items.length > page limit + 1 // false
  items.length > page limit // false

Tried items.length > page limit + 1 and items.length > page limit they both still return a false but there are definitely more items in the db.

Any pointers on how to go about this?

@Imad_Bouteraa Hello could you have a look at this please?

If you do not do any skip() you will always fetch the first page and never access the next page.

And items.length will never be bigger than page_limit because you limit the number of documents to page_limit so items.length will always be equal to page_limit except for the last page. The items.length will be smaller than page_limit.

2 Likes

Hello @steevej , hope you doing good

Hi @muhammed_ogunsanya
Pagination was always done with two requests. one to get the total and the other to get the actual documents (using skip and limit )
With aggregation you can do pagination with one pipeline using $group (the old way) or $facet

2 Likes

Thank you @steevej for you input!

1 Like

Hey Imad @Imad_Bouteraa Thank you for the explanation as always!

2 Likes