MongoDB 聚合 : How to get total records count?

标签 mongodb

我使用聚合从 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/

相关文章:

mongodb - 在 MongoDB 表达式中使用 $exists

python - 从 JSON 文件到 Numpy 数组

ruby-on-rails - 带有 "Foreign Key"的 Mongoid

node.js - MongoDB:如果不存在则插入文档,但如果已存在则跳过更新

node.js - 使用express js和mongodb发布插入多个数据

javascript - 为什么 Mongoose updateMany() 仅在使用 .then 时才起作用

mongodb - 将对象数组转换为 Mongoose 查询?

mongodb - 如何使用 interface{} 动态查询 mongodb

mongodb - 未在 mongo shell 中设置的变量

node.js - 如何使用 mongodb 指南针设置索引类型 'text'?