我使用聚合从 mongodb 获取记录。
$result = $collection->aggregate(array(
array('$match' => $document),
array('$group' => array('_id' => '$book_id', 'date' => array('$max' => '$book_viewed'), 'views' => array('$sum' => 1))),
array('$sort' => $sort),
array('$skip' => $skip),
array('$limit' => $limit),
));
如果我无限制地执行此查询,则将获取 10 条记录。但我想将限制保持为 2。所以我想获得总记录数。我该如何处理聚合?请给我建议。谢谢
最佳答案
从 v.3.4 开始(我认为)MongoDB 现在有了一个新的聚合管道运算符,名为 ' facet ' 用他们自己的话来说:
Processes multiple aggregation pipelines within a single stage on the same set of input documents. Each sub-pipeline has its own field in the output document where its results are stored as an array of documents.
在这种特殊情况下,这意味着可以执行以下操作:
$result = $collection->aggregate([
{ ...execute queries, group, sort... },
{ ...execute queries, group, sort... },
{ ...execute queries, group, sort... },
{
$facet: {
paginatedResults: [{ $skip: skipPage }, { $limit: perPage }],
totalCount: [
{
$count: 'count'
}
]
}
}
]);
结果将是(总共有 100 个结果):
[
{
"paginatedResults":[{...},{...},{...}, ...],
"totalCount":[{"count":100}]
}
]
关于MongoDB 聚合 : How to get total records count?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20348093/