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" : [
                -86.51557,
                33.584132
        ],
        "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")
 
 states.forEach(function(state){

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

   records.forEach(function(record){
     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.




Comments

Subscribe for latest tutorial updates

* indicates required

Popular posts from this blog

Preload Images Using Javascript

Preload Image is technique which helps browser to render images with minimum delay. Today we will see example of image gallery. Gallery contain 5 images which load images one after another whenever user clicks next and back button. This is a basic image gallery scenario which is used in all possible website, then why we need preloaded images for this gallery? Now a day’s most of website becoming faster and user expectation is increasing. Suppose your website doesn’t use preload image technique for gallery and a user visits any image gallery from Google Plus or Facebook and visits your website gallery. Then that user always prefer those websites rather than yours. Why? Because your website load one image at a time. When user click on next button, then only gallery load image and user has wait till it get loaded. To avoid this situation gallery needs to download all images

Spring Boot RestTemplate Guide with Example

What is RestTemplet? RestTemplate is a HTTP Client library that provides basic APIs for executing different HTTP type requests. RestTemplate is one of the HTTP libraries available on the market. The Spring Boot team designed and maintains it. As previously said, it is a client library, which means it may be utilised in our application as a stand-alone dependency. To utilise it, you don't require a complete Spring boot application. It's suitable for use in simple Java applications as well as other frameworks such as Micronaut, Play and others. Setup Add RestTemplate dependency to project, for this tutorial I am creating a simple java application to consume HTTP request and a node application to provide HTTP service. For Gradle build tool Add the following dependency in the build.gradle file . // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web implementation group: 'org.springframework.boot' , name: 'spring-boot-starter-w

CSS: How To Create Custom Scrollbar For Webkit Supported Browsers

In this tutorial, we will learn how to create a custom scroll bar using custom CSS styles. Custom scrollbars are becoming increasingly popular, and I'm excited to learn more about them. A scrollbar can be customised for a variety of reasons. The default scrollbar, for example, can make an app's UI look inconsistent across various versions of windows, thus we can benefit from having a single style here. This tutorial will help to create a custom scrollbar. Let's see how One of the most interesting aspects of these scrollbars is that they may be rendered in a variety of styles for different HTML elements on the same webpage. We will see the implementation of such a scrollbar for Webkit-supported browsers. First we will look at the basic CSS properties of the scrollbar. ::-webkit-scrollbar              ::-webkit-scrollbar-thumb        ::-webkit-scrollbar-track        ::-webkit-scrollbar-button       ::-webkit-scrollbar-track-piece  ::-webkit-scrollbar-cor