Skip to main content

MongoDB Tutorials : Aggregation Framework

MongoDB Aggregation Framework groups set of documents together and performs certain operation on this grouped documents and returns results in the form of documents.
MongoDB aggregation answer to those query which requires grouping of documents.

Aggregation framework works on three type of model
  • Aggregation pipeline
  • Map Reduce
  • Single Purpose Aggregation Operations

Now let see how MongoDB Aggregation Framework works with simple example.

Suppose you are MongoDB application developer in a respected company and you have been given a MongoDB database that holds information about human population which is distributed according to cities and their states.

here is one sample document.

        "city" : "ACMAR",
        "loc" : [
        "pop" : 6055,
        "state" : "AL",
        "_id" : "35004"

for this tutorial collection name is zips.

on first day your manager come and asks you to calculate total population of state DC.

your simplest approach to solve above query would be find all documents which have DC as state. then iterate them one by one and add population to a variable.
here is the a sample script

MongoDB script 1

 var record = db.zips.find( { "state" : "DC"} )
 var sum = 0;
 record.forEach(function(rec){ sum = sum + rec.pop })
 print("Total population of State DC = " + sum)

Total population of State DC = 606900

This works fine and given task is done.
later, next day your manager comes and tells you to find total population of each states.

now this query is little tricky, but you would modify you first MongoDB script and make it is given below.

MongoDB script 2

 var states = db.zips.distinct("state")

   var records = db.zips.find({"state" : state});
   var sum = 0;

     sum = sum + record.pop;

   print( state + " population: " + sum);

yes, it will give you expected result. no doubt you are a good MongoDB developer.

but you have put extra efforts get result. it does not mean that you are not a good developer, rather you are not aware of MongoDB aggregation framework which produce expected result in one query.

following is aggregation query

db.zips.aggregate([ { "$group" : { "_id" : "$state", "population" : { "$sum" :
 "$pop" } }} ])
it will give you same result which in equivalent of second MongoDB script.
now let see how it works.

First look out the group clause of aggregate query.

db.zips.aggregate([ { "$group" : { "_id" : "$state" } } ])
it will group collections according to state

as documents are grouped now we can perform calculation on them like summation of population.

db.zips.aggregate([ { "$group" : { "_id" : "$state", "population" : { "$sum" :
 "$pop" } }} ])

hence you get expected result in one query using MongoDB Aggregation Framework.


Popular posts from this blog

AngularJs Tutorial: Getting Started

This tutorial will help you to create a dynamic web application using power of AngularJs. ·   What is AngularJs AngularJs is javascript MVC framework (maintained by Google) which molds static HTML application to dynamic web application. That was a brief introduction, you can find more information on Wiki and AngularJS Site . AngularJs follows MVC pattern to separate out model from view and manage it by controller. See this image Goal of using AngularJs is to convert static HTML template to dynamic (Angular) template.   ·   How to convert static template to dynamic (Angular) Template Now consider the following static HTML template which contain list of movies title. <html> <head></head> <body>   <h1>Upcoming Movies</h1> <ul>     <li>       <span>Godzilla</span>     </li> <li>       <span>Batman vs Superman</span>     </li> <li>       <span>Sta

AngularJs Tutorials : Bootstrap

Every application starts with bootstrap process which initialize application and wire it other with dependencies and configurations. AngularJs is not different from other application. It also starts application with bootstrap process. Following operation happens inside AngularJs bootstrap process. Load application module. Create dependency injector and load dependencies. Compile HTML and create scope for application. All these steps happens inside angular.js scripting file. therefore we need to include it first. we can include it inside HEAD tag or at end of BODY tag. Note: Adding angular.js file at end of body tag will allow browser to load of HTML elements without any delay and afterwards load angular.js and begin bootstrapping process. You can get angular.js source file from <script src= ”” type= ”text/javascript” > AngularJs bootstrap process happens on docum

How to create SSH Key for GitHub and Bitbucket

This  post  demonstrate how to  generate  SSH private and  public   key  with fundamental steps and  assist   you  to  add   public   key  inside your  GitHub  and Bitbucket account. But first why we  need  this SSH  public   key ? Whether you are working in the team or an individual and you want make any operations on secure GIT repository like clone or push your latest changes then you require to provide your credentials to help GIT to authenticate you and approve those operations. But when  you  do so,  you  are  asked  to  provide  your username &  password ,  each   time  on  each   operation . It looks  simple  earlier, but later  becomes  a  headache . SSH  connection   helps   us  to  authenticate  using public and private keys, that  we  generate only once, later  we  don’t need to  authenticate ,  SSH  will  do  this behalf of  us . But how does it  work ? SSH   authenticate  you  using  an  identity , your  identity  and this  identity   comprise   combination  of p