MongoDB Aggregation Framework (part 4)

  • MongoDBAggregationFrameworkExamples2

This is the forth and last post of the serie about the MongoDB Aggregation Framework. We will continue with different queries. By the moment, we are going to use our five documents set inserted in our ‘aggfwktest’ collection.

Average computation in a new field

The highest and the lowest, the first and the last

Collecting values

We create arrays by this way:


The $unwind input is the output of the last example. We create a distinct document with every array value.:

Searching a text

We want to discover the hobbies that contains the string ‘an’:

Converting a text to uppercase

Adding array values

For this example we are going to create a document with the current accounts of a person, called Katherina, in an array. She will have three, one of them inactive. Afterwards, we are going to calculate its total cash.

Adding the value of distinct fields


Dividing the value of two fields:


In this example we set the value of a field depending on the value of other one:


This operator must be the last in the pipeline. It allows us to store the result of our query in a collection. If the collection does not exist it is created but if it does exist, its previous content is replaced. Let us see an example:


We know that we must set a geospatial index (2d or 2dsphere) before we can do geospatial searches.

$geoNear returns documents according to their proximity to a certain point, nearest first.

This operator deserves an exclusive post, therefore and without going into detail, I am going to show how this query would be:

The output of this query returns us the ten nearest places to a specific point, within a maximum distance of 5 kilometers. The output is made up of the place, the distance and its coordinates (‘loc’ field, defined as 2dsphere index).

This is the end of our MongoDB Aggregation Framework study. We could do a lot of examples but I think these are enough to understand its power, flexibility and easy to use. I wish that this four set of posts have been useful to learn how to use it and to understand it better.
As always, I am at your disposal for anything that you believe suitable.

Juan Roy

MongoDB Fan & Financial Software Developer

You may also like...

Leave a Reply