When it’s time to gather the metrics from MongoDB, there is no better solution than MongoDB aggregations. Aggregations are the functions that allow you to manipulate the data being returned from a MongoDB query. For example, aggregations operations can process the data records and return the computed results.
Mongodb Aggregate
Aggregate function groups the records in the collection and can be used to provide the total number(sum), average(avg), minimum(min), maximum(max), etc., out of the group selected.
Aggregation operations group values from multiple documents together and can perform various activities on the grouped data to return the single result. Aggregation bundles the data from multiple records and operates in many ways on those pooled data to return one combined result.
If we want to perform the aggregate function in MongoDB, aggregate() is the function to be used. Following is the syntax for aggregation:
db.collection_name.aggregate(aggregate_operation)
Now, let us take an example to understand the whole scenario.
Step 1: Install MongoDB on Mac
You can install MongoDB using homebrew using the following command.
brew install mongodb
After downloading Mongo, create the “db” directory. The db is the directory where the Mongo data files will live. You can create the folder in the default location by running the mkdir -p /data/db. Make sure that the /data/db directory has the right permissions.
You can start the mongodb daemon using the following command.
mongod
Now, run the MongoShell using the following command. Please keep open the MongoDB server and open the new tab of the terminal and type the following command.
mongo
Step 2: Let us create a database and create a collection.
We need to type the following queries inside the newly opened mongo shell terminal and not the mongo server. Type the following command to create a MongoDB database.
use myaggregate
Now, it will create a new database, and if existing, then switch to that database.
The next step is to create a mongo collection using the following command.
db.createCollection("stocks")
It will create a collection called stocks. First, insert the values inside the collection stocks. Then, type the following query inside the mongo shell.
db.stocks.insertMany([ { name: "Infosys", qty: 100, price: 800 }, { name: "TCS", qty: 100, price: 2000 }, { name: "Wipro", qty: 2500, price: 300 } ])
It will insert the three documents inside the stocks collection.
Now, we can fetch all the documents using the following query.
db.stocks.find().pretty()
You can verify that we have successfully inserted multiple data in the stocks collection.
Step 3: Mongodb Matching Documents.
The first stage of a pipeline is matching, and that allows us to filter out the documents so that we are only manipulating the documents that we care about. The matching expression looks and acts much like the MongoDB find function or the SQL WHERE clause.
db.stocks.aggregate([ { $match: { "price": 2000 } } ])
This will return the array of stocks that has a price of 2000. We can use the match stage in this way is no different from using the find method on the collection. Also, take another example of Match documents.
db.stocks.aggregate([ { $match: { "name": "Infosys" } } ]).pretty() { "_id" : ObjectId("5bd1a3839faa94f4a8a40920"), "name" : "Infosys", "qty" : 100, "price" : 800 }
Step 4: MongoDB Grouping Documents
Once we’ve filtered out the records we don’t want, we can start grouping together the ones that we do into useful subsets. We can also use groups to perform the operations across the common field in all documents, such as calculating the sum of a set of transactions and counting documents.
db.stocks.aggregate([{$group : {_id : "$qty", same_qty : {$sum : 1}}}])
In the above query, we will group those documents which have the same quantities. So it will give us the total number of documents which have the same quantities.
db.stocks.aggregate([{$group : {_id : "$qty", same_qty : {$sum : 1}}}]) { "_id" : 2500, "same_qty" : 1 } { "_id" : 100, "same_qty" : 2 }
The equivalent SQL is the following.
SELECT qty, SUM(qty) AS total FROM stocks GROUP BY same_qty
Different expressions used by an Aggregate function
Expression | Description |
---|---|
$sum | Add the defined values from all the documents in the collection. |
$avg | It calculates the average values from all the documents in the collection. |
$min | It returns the minimum of all values of documents in the collection. |
$max | It returns the maximum of all values of documents in the collection. |
$addToSet | Insert values to an array but no duplicates in the resulting document. |
$push | Insert values to an array in the resulting document. |
$first | Return the first document from the source document. |
$last | Return the last document from the source document. |
Step 5: Add sorting with a $sort
The $sort takes a document that specifies the field(s) to sort by and the respective sort order. <sort order>
Can have one of the following values:
- 1 to specify the ascending order.
- -1 to specify descending order.
{ $meta: "textScore" }
To sort by the computedtextScore
metadata in descending order. See Metadata Sort, for example.
db.stocks.aggregate([ { $group : {_id : "$qty", total : { $sum : 1 } } }, { $sort : {total : -1} } ]);
That’s it for this tutorial.
I am working on a project where i am using mongodb as a backend and angular2 for front end. I have two collections in db as Country{id, countryname} and state{id, statename} I want to find all the states depending on the country , I tried to write a code using $lookup but getting nothing. Also i need to use these two collections in an angular application for cascading dropdown. If i Select “India” only “States” in india should populate.I am new to mongodb. Plz help
I am working on a project where i am using mongodb as a backend and angular2 for front end. I have two collections in db as Country{id, countryname} and state{id, userId, statename} I want to find all the states depending on the country , I tried to write a code using $lookup but getting nothing. Also i need to use these two collections in an angular application for cascading dropdown. If i Select “India” only “States” in india should populate.I am new to mongodb. Plz help