如何在mongo的中间汇总阶段计算根文档的数量?

问题描述 投票:1回答:1

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

$limit

我不想进行2个查询,它们本质上是相同的,只是第一个查询返回文档计数,而其他查询返回文档本身。

所以结果将是这样的:

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

例如,将有10个{ documents: [...], totalMatchedDocumentsCount: x } ,但documents可能是totalMatchedDocumentsCount

我不知道如何执行此操作,我看不到500方法返回游标。是否可以在一个查询中实现我想要的?

mongodb pagination aggregation-framework aggregate
1个回答
0
投票
您需要aggregate,并且可以将$facet$limit作为一个子管道来运行管道,而$skip可以同时使用:

$count

© www.soinside.com 2019 - 2024. All rights reserved.