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

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

I strongly recommend you take MongoDB Courses and Trainings | MongoDB University. These kind of aspects are covered. In the mean time take a look at https://www.mongodb.com/docs/manual/reference/method/cursor.skip/.

Thanks for this helpful tips

2 Likes