Taking sum of “column” in MongoDB

后端 未结 7 526

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 fin

相关标签:
7条回答
  • 2020-12-10 19:56

    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.

    1. Use Map/Reduce. This is the general method for doing sums, counts, averages, etc across a data set. This is not trivial, you will need to read the documentation to understand how this works.
    2. Aggregation. This is a special framework for doing "mini-Map/Reduce" jobs. The group example clearly demonstrates how to do "sum by type". You simply need to convert the command to PHP.
    3. The Aggregation Framework. This is currently only in the unstable build (2.1.0). This will be better than option #2, but it will only work on 2.1+.

    ... so please give PHP code to make this work

    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.

    0 讨论(0)
提交回复
热议问题