Latest Code Tutorials

Mongodb Aggregate Example Tutorial

0 865

Get real time updates directly on you device, subscribe now.

Mongodb Aggregate Example Tutorial is today’s leading topic. When it’s time to gather the metrics from MongoDB, there is no better solution than MongoDB aggregations. Aggregations are the set of functions that allow you to manipulate the data being returned from a MongoDB query. Aggregations operations can process the data records and return the computed results. Aggregation operations group values from multiple documents together and can perform a variety of 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.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program

Mongodb Aggregate Example Tutorial

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.

If we want to perform the aggregate function in MongoDB, The aggregate() is the function to be used. Following is the syntax for aggregation:


Now, let us take an example to understand the whole scenario.

#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.



Mongodb Aggregate Example Tutorial

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.



MongoDB Aggregation Example

#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.

Next step is to create a mongo collection using the following command.


It will create a collection called stocks. Insert the values inside the collection stocks. Type the following query inside the mongo shell.

   { 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.


You can verify that we have successfully inserted the multiple data in the stocks collection.

#3: Mongodb Matching Documents

The first stage of a pipeline is matching, and that allows 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.

  { $match: { "price": 2000 } }


Mongodb Matching Documents

This will return the array of stocks that has price 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

#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 has 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 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.

#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 computed textScore metadata in descending order. See Metadata Sort for example.
  { $group : {_id : "$qty", total : { $sum : 1 } } },
  { $sort : {total : -1} }


MongoDB document sorting

Finally, Mongodb Aggregate Example Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.