MongoDB 聚合:如何获得总记录数? [英] MongoDB Aggregation: How to get total records count?

查看:204
本文介绍了MongoDB 聚合:如何获得总记录数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用聚合从 mongodb 中获取记录.

$result = $collection->aggregate(array(数组('$match' => $document),数组('$group' => array('_id' => '$book_id', 'date' => array('$max' => '$book_viewed'), 'views' => array('$sum' => 1))),数组('$sort' => $sort),数组('$skip' => $skip),数组('$limit' => $limit),));

如果我无限制地执行此查询,则将获取 10 条记录.但我想将限制保持为 2.所以我想获得总记录数.我该如何处理聚合?请给我建议.谢谢

解决方案

自从 v.3.4(我认为)MongoDB 现在有了一个新的聚合管道操作符,名为 'facet' 用他们自己的话来说:

<块引用>

在同一组输入文档的单个阶段内处理多个聚合管道.每个子管道在输出文档中都有自己的字段,其结果存储为文档数组.

在这种特殊情况下,这意味着可以执行以下操作:

$result = $collection->aggregate([{ ...执行查询,分组,排序... },{ ...执行查询,分组,排序... },{ ...执行查询,分组,排序... },{$facet:{paginatedResults: [{ $skip: skipPage }, { $limit: perPage }],总数: [{$count: '计数'}]}}]);

结果将是(对于前 100 个总结果):

<预><代码>[{分页结果":[{...},{...},{...}, ...],totalCount":[{count":100}]}]

I have used aggregation for fetching records from 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),
));

If I execute this query without limit then 10 records will be fetched. But I want to keep limit as 2. So I would like to get the total records count. How can I do with aggregation? Please advice me. Thanks

解决方案

Since v.3.4 (i think) MongoDB has now a new aggregation pipeline operator named 'facet' which in their own words:

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.

In this particular case, this means that one can do something like this:

$result = $collection->aggregate([
  { ...execute queries, group, sort... },
  { ...execute queries, group, sort... },
  { ...execute queries, group, sort... },
  {
    $facet: {
      paginatedResults: [{ $skip: skipPage }, { $limit: perPage }],
      totalCount: [
        {
          $count: 'count'
        }
      ]
    }
  }
]);

The result will be (with for ex 100 total results):

[
  {
    "paginatedResults":[{...},{...},{...}, ...],
    "totalCount":[{"count":100}]
  }
]

这篇关于MongoDB 聚合:如何获得总记录数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆