如何计算 mongo 中聚合阶段的根文档数量?



我想在网站上实现分页,我希望我的 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
}

这样会有例如 10documentstotalMatchedDocumentsCount可能是500.

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

您需要$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"
}
])

最新更新