【问题标题】:How to count number of root documents in intermediate aggregate stage in mongo?如何计算mongodb中间聚合阶段的根文档数?
【发布时间】:2020-05-11 12:24:55
【问题描述】:

我想在网站上实现分页,我希望我的 mongodb 查询首先返回执行 2 个集合之间的查找,对文档进行排序,计算文档总数,然后在 $skip 之后返回相关文档和$limit 聚合中的阶段。这是我的查询:

const res = await Product.aggregate([
  {
    $lookup: {
      from: 'Brand',
      localField: 'a',
      foreignField: 'b',
      as: 'brand'
    }
  },
  {
    $sort: {
      c: 1,
      'brand.d': -1
    }
  },
  {
    $skip: offset
  },
  {
    $limit: productsPerPage
  }
])

我不想进行 2 个基本相同的查询,仅第一个查询返回文档数,另一个查询返回文档本身。

所以结果会是这样的:

{
  documents: [...],
  totalMatchedDocumentsCount: x
}

例如会有 10 个documents,但totalMatchedDocumentsCount 可能是500

我不知道该怎么做,我没有看到 aggregate 方法返回光标。是否有可能在一个查询中实现我想要的?

【问题讨论】:

  • 这是否回答了您的问题:stackoverflow.com/questions/51029987/… ?
  • @mickl 谢谢,在某种程度上确实如此,但在您引用的解决方案中,我将在每个文档中都有计数,这不是很有效,因为我只需要在根级别上计数一次文档。我想我需要对文档进行分组,然后添加一个总计数字段并删除每个文档的总计数,但这似乎效率极低。

标签: mongodb pagination aggregation-framework aggregate


【解决方案1】:

您需要$facet,并且可以将$limit$skip 作为一个子管道运行您的管道,而$count 可以同时使用:

const res = await Product.aggregate([
    // $match here if needed
    {
        $facet: {
            documents: [
                {
                    $lookup: {
                    from: 'Brand',
                    localField: 'a',
                    foreignField: 'b',
                    as: 'brand'
                    }
                },
                {
                    $sort: {
                    c: 1,
                    'brand.d': -1
                    }
                },
                {
                    $skip: offset
                },
                {
                    $limit: productsPerPage
                }
            ],
            total: [
                { $count: "count" }
            ]
        }
    },
    {
        $unwind: "$total"
    }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2019-04-06
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多