lem*_*oe9 4 php math sum mongodb
在MySQL中,我只需要"SELECT sum(pts)FROM table"来获取表中pts列的总和.但是,我正在将此应用程序转换为MongoDB,并且无法找到一种直接的方法来获取我的集合中的公共密钥"type"的总和.我正在使用PHP,所以请提供PHP代码以使其工作.
这是我的数据:
{ "_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" }
Run Code Online (Sandbox Code Playgroud)
如何获得$ sum等于"type"键的总和?
利用MongoDB的新聚合框架:
$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
),
));
Run Code Online (Sandbox Code Playgroud)