fastapi mongodb how to add pagination and limit number of items per page?

Question:

I am using pymongo. Category.city_collection.find() getting all collection of result. But I want to show only 5 result per page. I tried this Category.city_collection.find().limit(5) which showing 5 result on first page but how to go others page like second page, third page etc? I am using mongo db with my fastapi project. here is my full code

@router.get('/all_city')
async def all_city():
   
      all_category = Category.city_collection.find() 
      category = convert_json(all_category)
      return category
Asked By: boyenec

||

Answers:

You need to use skip and limit

With skip, you set the number of documents that you will skip.

With limit, you set the page size.

Example:

db.test.find({}).skip(10).limit(10)

Would return the 2nd page in 10 document page sizes.

A skip(20).limit(10), would return the 3rd page…

Most of the times you should use this methods over ordered data.

Answered By: James