简体   繁体   English

如何对 MongoDB 集合中的子文档进行分页?

[英]How to paginate subdocuments in a MongoDB collection?

I have a MongoDB collection with the following data structure;我有一个具有以下数据结构的 MongoDB 集合;

[ 
  {  
    "_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.如您所见,每个企业的评论都是集合中的一个子文档,其中 businessName1 共有 2 条评论。 In my real MongoDB collection, each business has 100s of reviews.在我真实的 MongoDB 收藏中,每个商家都有 100 条评论。 I want to view only 10 on one page using pagination.我想使用分页在一页上只查看 10 个。

I currently have a find_one() function in Python that retrieves this single business, but it also retrieves all of its reviews as well.我目前在 Python 中有一个 find_one() function 检索这个单一的业务,但它也检索它的所有评论。

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.我知道 Python 中的skip()limit()方法,您可以在其中限制检索结果的数量,但据我所知,您只能在 find() 方法上执行这些方法. Is this correct?这个对吗?

Option 1: You can use $slice for pagination as follow:选项 1:您可以使用$slice进行分页,如下所示:

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

Playground操场


Option 2: Or via aggregation + total array size maybe better:选项 2:或者通过聚合 + 总数组大小可能更好:

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

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM