Taking sum of quot;columnquot; in MongoDB(取“列的总和在 MongoDB 中)
问题描述
在 MySQL 中,我只需执行SELECT sum(pts) FROM table"即可获取表中 pts 列的总和.但是,我正在将此应用程序转换为 MongoDB,并且找不到一种直接的方法来获取我的集合中的公共键类型"的总和.我正在使用 PHP,所以请提供 PHP 代码来完成这项工作.
In MySQL, I would simply go "SELECT sum(pts) FROM table" to get the sum of the pts column on the table. However, I am converting this application to MongoDB and cannot find a straightforward way to get a sum of the common key "type" in my collection. I am using PHP, so please give PHP code to make this work.
这是我的数据:
{ "_id" : ObjectId("4f136dab5056f65b61000000"), "p_id" : "3", "g_id" : "1", "type" : "3" }
{ "_id" : ObjectId("4f136dad5056f65760000000"), "p_id" : "8", "g_id" : "1", "type" : "7" }
{ "_id" : ObjectId("4f136daf5056f65860000000"), "p_id" : "6", "g_id" : "1", "type" : "4" }
{ "_id" : ObjectId("4f136db15056f65460000000"), "p_id" : "27", "g_id" : "1", "type" : "2" }
如何让 $sum 等于type"键的总和?
How can I get $sum to equal the total of the "type" key?
推荐答案
利用 MongoDB 新的 聚合框架:
Utilizing MongoDB's new Aggregation Framework:
$result = $db->command(array(
'aggregate' => 'COLLECTION_NAME',
'pipeline' => array(
// Match:
// We can skip this in case that we don't need to filter
// documents in order to perform the aggregation
array('$match' => array(
// Criteria to match against
)),
// Group:
array('$group' => array(
// Groupby fields:
'_id' => "$fieldname1, $fieldname2, $or_empty, $etc",
// Count:
'count' => array('$sum' => 1),
// Sum:
'type_sum' => array('$sum' => '$type'),
))
// Other aggregations may go here as it's really a PIPE :p
),
));
这篇关于取“列"的总和在 MongoDB 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:取“列"的总和在 MongoDB 中


基础教程推荐
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- php中的foreach复选框POST 2021-01-01
- Web 服务器如何处理请求? 2021-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php中的PDF导出 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01