pythonmongodblimitskipsubdocument

How to paginate subdocuments in a MongoDB collection?


I have a MongoDB collection with the following data structure;

[ 
  {  
    "_id": "1",
    "name": "businessName1",
    "reviews": [
      {
        "_id": "1",
        "comment": "comment1",
      },
      {
        "_id": "2",
        "comment": "comment1",
      },
     ...
    ]     
  } 
]

As you can see, the reviews for each business are a subdocument within the collection, where businessName1 has a total of 2 reviews. In my real MongoDB collection, each business has 100s of reviews. I want to view only 10 on one page using pagination.

I currently have a find_one() function in Python that retrieves this single business, but it also retrieves all of its reviews as well.

businesses.find_one( \
        { "_id" : ObjectId(1) }, \
        { "reviews" : 1, "_id" : 0 } )

I'm aware of the skip() and limit() methods in Python, where you can limit the number of results that are retrieved, but as far as I'm aware, you can only perform these methods on the find() method. Is this correct?


Solution

  • Option 1: You can use $slice for pagination as follow:

    db.collection.find({
     _id: 1
    },
    {
     _id: 0,
     reviews: {
       $slice: [
        3,
        5
       ]
     }
    })
    

    Playground


    Option 2: Or via aggregation + total array size maybe better:

    db.collection.aggregate([
     {
      $project: {
      _id: 0,
      reviews: {
        $slice: [
          "$reviews",
          3,
          5
        ]
      },
      total: {
        $size: "$reviews"
      }
     }
    }
    ])
    

    Playground