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:
MongoDB does not have a single simple query for performing a sum.
In MongoDB you will need to run a special command for this. You have three options.
group
example clearly demonstrates how to do "sum by type". You simply need to convert the command to PHP.No simple snippet of PHP code here, aggregation is actually a complex topic in MongoDB.
First you have to pick one of the methods (#1, #2, #3) and then you have to decide what you plan to do with the output. For example, #1 Map/Reduce, can create a new collection with the aggregates or it can return the values in line, but only 10k values can be returned. Option #2 will runs in serial and will be very slow on sharded servers. Option #3 is still in "beta" and will eventually replace #2.
In any case, all of the options will require further reading before you pick a plan of attack.
Another solution is to create a script in the database, that will sum the require data and return your result something like:
The Script
PHP
In php after setting the connection with the db, it will be something like:
Look this tutorial to learn more about scripting in mongo with php.
http://pointbeing.net/weblog/2010/08/getting-started-with-stored-procedures-in-mongodb.html
More detail click here
This can be done with the following map reduce functions:
or in php:
Other answers have already given lot many sources. Just giving answer for asked question: