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.
Here is my data:
{ "_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" }
How can I get $sum to equal the total of the "type" key?
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
),
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With