The aggregation framework
The aggregation framework of MongoDB was introduced from MongoDB v2.0. It gives us similar functionality, such as the GROUP BY
in SQL. This could be achieved easily by using MapReduce, but the aggregation is simpler!
Mongoid currently provides only the following basic aggregations: :count
, :min
, :max
, :sum
, and :avg
.
So, to get a count of all the books use the following code:
irb> Book.count => 12 irb> Book.avg(:reviews_count) => 1.3333333333333333
The aggregation framework will be discussed in detail in the next chapter. In short, it uses an pipeline that streams output from one operation as the input of the next operation in the pipeline (similar to the |
operator on the Unix shell). Though Mongoid supports the basic aggregations, we can also define our own complex aggregation pipelines. However, the aggregate method is not directly available on the models (as yet). Instead, we need to invoke it on the collection. Let's see an example that shows how...