For more complex queries and data manipulation in MongoDB, we can use the aggregation framework. First introduced in MongoDB V2.2 (the current version as of this writing is V3.6) the aggregation framework creates a pipeline of operations to perform on documents1. Pipelines support operations such as sorting, filtering, and grouping documents similar to a SQL
GROUP BY clause. Pipelines also enable grouped data manipulation, creating entirely new collections in the process. I used the tree database from my first and second MongoDB discoveries to explore the aggregation framework.
If you remember from my previous posts, each tree has a type and a grade which specifies the height of the tree. One piece of information I'm curious about is the total number of trees in each grade with type frazier fir. The aggregation function to answer my question is written like so:
aggregate() function takes an array of pipeline steps. The first step matches on type frazier. The seconds step groups all matched documents by grade and gets the number of documents in each group. The final step sorts each group by the count. These three steps are performed with the
$sort operators respectively.
Grouping is not restricted to a single property. To group by multiple properties, each property is added to the
_id object. In the next example I grouped the aggregate by type and grade. Also since I matched on the entire collection, I excluded the
$match pipeline step.
$group operations can exist in an aggregation pipeline. In the next pipeline I get all the tree statistics - count, expenses, revenue, and profits. Since I don't want the result of this aggregation to go to waste, I saved its result to a new collection with the
$out operator. I simply specified the name of the collection to save the output to (
treestat). I also used the
$project operator to structure and pick the properties for the output collection. All properties specified in the
$project step are passed to the next step in the pipeline.
One important thing to note about the
$out operator is it completely replaces the existing collection with the result of the aggregation2. This can accidentally wipe out an entire collection. Be careful!
Finally I got the tree count, expenses, revenue, and profits for all trees using the newly created
The aggregation framework is very powerful. You can even use it to create a pseudo
JOIN operation between collections3! The source code for this discovery is on GitHub.