Search code examples
mongodbpaginationlimit

page limit in MongoDB


I am working on a mobile app backend and using MongoDB for storing data. I have implemented pagination in MongoDB and it is working fine. Now, I have a requirement which is explained below. The scenario is as follows:

  • A User can have two categories.(User collection - contains user profile information)
  • In each category, user can upload images.(Images collection - contains all the uploaded images of all the users)

On home page of the app, it is required to show 10 images per category.(20 images total).

When I am querying MongoDB, I am using OR operation on category_id in Image Collection, and using limit to return 20 images. Obviously, it will return 20 images combined of both the categories. Is it possible to return 10 images per category in single query?


Solution

  • OR isn't what you want. OR will pick every result that matches either option. OR doesn't care how many of each category it matched, as long as it got to it's limit.

    To the best of my knowledge, you must perform two separate queries, one for each category.

    You might be able to pull something off with aggregation, but I have no idea how that would play out.

    If you ask me, performing two dead simple queries may surprisingly outperform many tricks.