In this article we will look at Mongo DB aggregations. The syntax is slightly complex, but we will try to break it down into simple sections and see how to use the power of aggregations while querying Mongo DB.
First, let us begin with a simple example. Let us count the number of books written by anonymous authors. Use the following Mongo DB aggregation query.
db.Books.count({author:"Anonymous"});
That one above was quite simple and self explanatory. Now let us take another simple example. Let us find out a list of distinct publishers. Use the following Mongo DB aggregation query.
db.Books.distinct("publisher");
Now let us look at a little more complex query. Let's calculate the number of books per publisher. The Mongo DB aggregate query would look like the one below.
db.Books.aggregate(
[
{$match: {} },
{$group: {_id: "$publisher", title: {$count: "$title"} } }
]
);
In the above query notice that there are two major parts. The first part, the '$match' portion of the query is used to specify the filter condition. Here we fetched all the documents in the collection. You may use this as per your specific requirement.
In the second part, the '$group' portion of the query notice that we are specifying two sub-items: the '_id' specifies the attribute on which grouping will be done before aggregation can occur. Whereas, the second part specifies the actual attribute whose values will be aggregated.
So in the above query we are instructing the Mongo DB engine to group by 'publisher' and find out the 'count' (i.e. number) of 'title' (i.e. books).
You may also apply some sorting along with Mongo DB aggregate queries as shown below. The below query will sort the output of the Mongo DB aggregation query in ascending order. Note that for descending order sorting we can use -1.
db.Books.aggregate(
[
{$match: {} },
{$group: {_id: "$publisher", title: {$count: "$title"} } }
{$sort: {total: 1} }
]
);