MongoDB Aggregation Framework (part 3)

Part III of the post MongoDB Aggregation Framework


After a brief and theoretical introduction to the Aggregation Framework philosophy, and its odds, we are going to begin with what is really important for us, the examples.

Single purpose aggregation operations

Count y Distinct are the operations we are most used to because they are similar to the sql world.

First we must insert these documents to use them later with the examples:


As you can suppose this operation returns us the number of documents that match a given condition.


With distinct we obtain the unique values of a specific field, for example:


The result of the next query is the ‘score’ field summatory, per ‘user_id’, except those documents in which the field value is less than 6:

We can also do this query with $match, $group operations and $sum accumulator.


This operation let us select the fields we want to obtain. In the next example we will not select the _id nor the ‘score’ field.


We use $match to set the conditions to fulfill:


We are going to concatenate two stages in our next example. In the first one we will extract those documents that match a condition. Only these will be the input to the second stage, that will sort them according the value of the ‘score’ field. The value ‘1’ will sort the results in ascending order and the value ‘-1’ will do it in descending order:


We will use accumulators ($sum, $avg, etc) with $group:

We have only added the value of the ‘score’ field of all documents. Now let us group the documents by user_id:

$match as sql ‘having’

Leave a comment

Your email address will not be published. Required fields are marked *

six + 17 =