Introduction
Welcome back to the MongoDB article series - Part 7. In the previous article, we discussed the advanced index concept in MongoDB. We have also discussed capped collections, TTL index, Full-Text Index, etc. Now, in this article, we will discuss how to implement the aggregation framework concepts in a MongoDB Database. If you want to read the previous articles of this series, then follow the links.
In the previous article, we have discussed the index in MongoDB. Now, in this article, we will discuss the aggregation framework in MongoDB, and also, we will see how we can use this in our data searching query. So, Data Aggregation is one kind of process where all types of information are collected and then represented in a summary format. The main purpose of the data aggregation is doing the analysis work like statistical analysis, comparison analysis, computations, etc.
Aggregation Frameworks
In MongoDB, the aggregation framework is mainly used for displaying results for the statistical and analytical analysis of data. This framework always provides us with the transformation of a document within a collection. Basically, the aggregation framework builds a pipeline that processes the data through several blocks of aggregation framework like – filtering, projecting, grouping, sorting, limiting, and skipping. This operation always processes the data from the documents and returns the projected results. This framework groups all the data from the different multiple documents together and then performs a variety of operations on this grouped data to return a single result.
The aggregate framework always returns an array as a result of the documents. This makes the aggregation framework as an alternative knowledge flow pipeline. It actually acts as a process flow. This framework first performs the transformation of documents and then combines the documents within a collection and returns the output. Every operator in an aggregation framework receives a stream of documents, then performs some kind of transformation on these documents, and then passes on the results of the transformation to the users. If it's the last pipeline operator, then the result returns to the user directly. Otherwise, the result is passed to the next transformation process as an input. Operators may be combined in any order and recur again and again as necessary. For instance, you'll perform "$match", "$group", and then again "$match" once more with totally different criteria.
The MongoDB aggregation pipeline always consists of stages. Every stage transforms the documents as they submit them to the pipeline. Pipeline stages don't get to turn out one output document for each input document, e.g. some stages might generate new documents or filtered documents as a result. Pipeline stages will execute multiple times within the pipeline. MongoDB provides the db.collection.aggregate() methodology within the data collections and therefore the combination command for aggregation pipeline.
$Project
Projection is one of the additional powerful syntaxes within the aggregation pipeline. It is mainly used in the aggregation pipeline rather than using it as a “normal” command syntax. "$project" permits you to extract fields from subdocuments, rename fields, and perform attention-grabbing operations on them. The simplest operation "$project" will perform is solely choosing fields from your incoming documents to incorporate or exclude a field, use the identical syntax you have used in the second argument of a command. In the below example, the syntax will return only those documents as a result that contains the field "author" within the collection.
- db.articles.aggregate({"$project" : {"author" : 1, "_id" : 0}})
In the above syntax, “author” is used to represent the fieldname value within the aggregation framework. For example, "$age" would get replaced with the contents of the age field (and most likely be variety, not a string), and "$tags.3" would get replaced with the fourth component of the tags array. Thus, "$_id" is replaced by the "_id" field of every document coming back through the pipeline. Note that we just need to specifically exclude "_id" field so that it will not return as part of the result to the user. We'll be able to use this syntax to make multiple copies of a field for later use in an exceedingly "$group", say.
- db.users.aggregate({"$project" : {"userId" : "$_id", "_id" : 0}})
- Mathematical Expression Arithmetic expressions allow you to manipulate numeric values. You typically use these expressions by specifying an associate array of numbers to control. For example, the subsequent expression will calculate the total value of the "salary" and "bonus" fields. These are the syntax of each expression.
- $add (expr1[, expr2, ...]) - Accepts one or more expressions and adds them together
- $subtract (expr1, expr2) - Accepts two expressions and subtracts the second from the first.
- $multiply (expr1[, expr2, ...]) - Takes one or more expressions and multiplies them together.
- $divide (expr1, expr2) - Takes two expressions and divides the first by the second.
- $mod (expr1, expr2) - Takes two expressions and returns the remainder of dividing the first by the second.
- Date ExpressionSometimes, we need to performs aggregations command on the time-based unit value like - What was happening last week? Or Last month? Or Over the last year? Therefore, aggregation features a set of expressions that may be used to extract date info in some additional helpful ways like "$year", "$month", "$week", "$dayOfMonth", "$dayOfWeek", "$dayOfYear", "$hour", "$minute", and "$second". So we can solely use date operations on fields that basically contain data type value.
- String ExpressionThere are a couple of basic string operations which we need to perform some times. Their signatures are as follows,
-
$substr (expr, startOffset, numToReturn)This returns a substring of the primary argument, beginning at the startOffset-th computer memory unit and together with consequent numToReturn bytes (note that this is often measured in bytes, not characters, therefore multibytes encodings can watch out of this). expr must be valuable to a string.
-
$concat (expr1[, expr2, ..., exprN])Concatenates each string expression (or string) given.
-
$toLower (expr)Returns the string in lower case. expr must evaluate to a string.
-
$toUpper (expr)Returns the string in upper case. expr must evaluate to a string
Sample Example of $add
- db.employees.aggregate({
- "$project": {
- "totalPay": {
- "$add": ["$salary", "$allowances"]
- }
- }
- })

Rushi MehtaPosted Nov 13, 2018, 2:41 AM
Nice Article written..