【问题标题】:MongoDB paginate in aggregate query聚合查询中的MongoDB分页
【发布时间】:2020-12-05 03:59:57
【问题描述】:

我在 MongoDB 中有以下集合

个人资料集合

> db.Profile.find()
{ "_id" : ObjectId("5ec62ccb8897af3841a46d46"), "u" : "Test User", "is_del": false }

商店收藏

> db.Store.find()
{ "_id" : ObjectId("5eaa939aa709c30ff4703ffd"), "id" : "5ec62ccb8897af3841a46d46",  "a" : { "ci": "Test City", "st": "Test State" }, "ip" : false }, "op" : [ ], "b" : [ "normal" ], "is_del": false}

物品收藏

> db.Item.find()
{ "_id" : ObjectId("5ea98a25f1246b53a46b9e10"), "sid" : "5eaa939aa709c30ff4703ffd", "n" : "sample", "is_del": false}

这些集合之间的关系定义如下:

  1. Profile -> Store:是1:n 关系。 Store 中的 id 字段与 Profile 中的 _id 字段相关。
  2. Store -> Item:也是1:n关系。 Item 中的 sid 字段与 Store 中的 _id 字段相关。

我有一个查询要查找所有配置文件商店以及每个商店的Item 计数。查询如下(我从the answer得到的)

db.Profile.aggregate([
  {
    $match: { is_del: false }
  },
  {
    $lookup: {
      from: "Store",
      as: "stores",
      let: {
        pid: { $toString: "$_id" }
      },
      pipeline: [
        {
          $match: {
            is_del: false,
            $expr: { $eq: ["$$pid", "$id"] }
          }
        },
        {
          $lookup: {
            from: "Item",
            as: "items",
            let: {
              sid: { $toString: "$_id" }
            },
            pipeline: [
              {
                $match: {
                  is_del: false,
                  $expr: { $eq: ["$$sid", "$sid"] }
                }
              },
              {
                $count: "count"
              }
            ]
          }
        },
        {
          $unwind: "$items"
        }
      ]
    }
  }
])

现在,我需要对结果进行分页。如何在汇总结果中分页?什么是可扩展的方法?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    我相信你必须添加

    {
        $limit: limit
    }, {
        $skip: skip
    }
    

    之后

    {
        $unwind: "$items"
    }
    

    基本上,在您想要限制查询的查询级别上,假设 10 个元素,但先跳过 5 个元素(您为第二页加载记录,每页 5 个记录)。我相信您每次都必须计算limitskip

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-19
      • 2019-06-18
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多