NoSQLZoo

AGGREGATE examples

aggregate

The aggregate function takes a list of operations (or a single operation) - this is the pipeline.

The data passes through each stage of the pipeline in turn.

The result is a list of items.

Pipeline stages can include:

1$group

$group allows you to collect group items that share common features

List the continents, give the country count and total population

db.world.aggregate(
    {$group: {
        _id: "$continent",
        pop: {$sum: '$population'},
        num: {$count: {}},
    }}
);

2$match

$match performs queries in a similar way to find()

Show all the details for France

db.world.aggregate([
    {$match: {name: "France"}}
]);
db.world.aggregate([{$match:{name:"France"}}]);

3$limit

$limit sets the amount of documents to be handed to the next stage in the pipeline.

Return the first two documents

db.world.aggregate([
    {$limit: 2}
]);
db.world.aggregate([{"$limit":2}]);

4$project

$project selects what fields to display. It can also create new fields and compare fields against each other without using $where.

Show the name and population density of all Asian countries. (population/area)

Note that "density" is a new field made from the result of dividing two existing fields, and that $divide is an inbuilt function.

To avoid dividing by 0 insert a $match to remove any countries with no area (Vatican City), then pipe these results through to $project.

There is no need to check if values are null, MongoDB will ignore these documents.

db.world.aggregate([
    {$match: {area: {$ne: 0}, continent: "Asia"}},
    {$project: {
        _id: 0,
        name: 1,
        density: {$divide: ["$population", "$area"]}
    }}
]);
db.world.aggregate([{"$match":{"area":{"$ne":0},"continent":"Asia"}},{"$project":{"_id":0,"name":1,"density":{"$divide":["$population","$area"]}}}]);

5aggregate composition

You can have several pipeline stages, the data flows through each one in turn.

Show the name of Asian countries with a density that's over 500 people per km2. (population/area)

db.world.aggregate([
   {$match: {area: {$ne: 0}, continent: "Asia"}},
   {$project: {
       _id: 0,
       name: 1,
       density: {$divide: ["$population", "$area"]}
   }},
   {$match: {density: {$gt: 500}}}
]);
db.world.aggregate([{"$match":{"area":{"$ne":0},"continent":"Asia"}},{"$project":{"_id":0,"name":1,"density":{"$divide":["$population","$area"]}}},{"$match":{"density":{"$gt":500}}}]);

6$sort

$sort allows ordering of the results set, where 1 is ascending and -1 is descending. Note that not including $match is the same as {"$match":{}}

Show the top five countries by population in descending order (the data set may be out of date)

db.world.aggregate([
    {$sort:{
        "name":-1
    }},
    {$limit:5},
    {$project:{
        "_id":0,
        "name":1,
    }},
]);

Grouping

Grouping provides accumulator operations such as $sum. All groups must have an _id. To see why this is useful imagine the following:

So far you've been using the world collection. As every country has a continent, it would make sense to have countries as a nested document inside continents: e.g:

[
    {"name": "Africa",
     "countries": [
         {"name": "Algeria",     "capital": "Algiers",    ...},
         {"name": "Angola",      "capital": "Luanda",     ...},
         {"name": "Benin",       "capital": "Porto-Novo", ...}.
         {...},
         ...
    ]},
    {"name": "Asia",
     "countries": [
         {"name": "Afghanistan", "capital": "Kabul",  ...},
         {"name": "Azerbaijan",  "capital": "Baku",   ...},
         {"name": "Bahrain",     "capital": "Manama", ...},
         {...},
         ...
    ]},
    {...},
    ...
]

The world collection isn't like this however. It uses the following structure, which has a redundancy where continent is repeated for each country.

[
    {"name": "Afghanistan", "capital": "Kabul",   "continent": "Asia",   ...},
    {"name": "Albania",     "capital": "Tirana",  "continent": "Europe", ...},
    {"name": "Algeria",     "capital": "Algiers", "continent": "Africa", ...},
    {...},
    ...
]

The code to group by continent is "_id":"$continent". If instead the question was to group by country the code would be "_id": "$name". To operate over the whole collection as one group, use "_id": null.

7group operators

$max and $min can be used to get the largest and smallest values in a group.

Get the smallest and largest GDPs of each continent.

db.world.aggregate([
    {$group: {
        _id: '$continent',
        lst: {$push: {n:"$name",c:"$capital"}},
    }}
]);

8Multiple aggregate functions

Some other useful aggregate functions to know are $sum and average: $avg. The example below combines previous example material.

Order the continents in descending order by total GDP, Include the average GDP for each country.

db.world.aggregate([
    {$match: {}},
    {$group: {
        _id:"$continent",
        "Total GDP": {"$sum": "$gdp"},
        "Average GDP": {"$avg": "$gdp"}
    }},
    {$sort: {
        "Total GDP":-1
    }},
    {$project:{
        "Area": "$_id",
        "Total GDP": 1,
        "Average GDP": 1,
        _id: 0
    }}
]);
db.world.aggregate([{"$group":{"_id":"$continent","Total GDP":{"$sum":"$gdp"},"Average GDP":{"$avg":"$gdp"}}},{"$sort":{"Total GDP":-1}},{"$project":{"Area":"$_id","Total GDP":1,"Average GDP":1,"_id":0}}]);

9Using Conditions

$cond is similar to a CASE statement in other languages. It has the form "$cond": [{<comparison>: [<field or value>, <field or value>]}, <true case>, <false case>]

db.world.aggregate([
    {$group: {
        _id: {
            $cond: [{"$eq": ["$continent", "Eurasia"]}, "Europe", "$continent"]
        },
        area: {$sum: "$area"}
    }},
    {$sort: {
        area: -1
    }},
    {$project: {
        _id: 1,
        area: 1
    }}
]);