Web Analytics using MongoDB Aggregation Framework

Prior to version 2.1, if you wanted to do aggregation in MongoDB (grouping documents by key(s), finding total and average values etc.) you had to use MapReduce. Although a flexible and powerful tool for data analysis, many programmers (including myself) find using it unintuitive. It takes some effort to fully grasp its underlying concepts, before you start wielding its true power. Also performing MapReduce in an application development language (other than JavaScript), feels a bit ‘hackish’, to say the least. You have to write your map and reduce functions in JavaScript, use the code as native strings in your application which have to be sent to the MongoDB server through the driver. If the map and reduce are complex, the readability and maintainability of your entire application code may take a hit. The Aggregation Framework provides flexible way to specify and execute aggregation queries in MongoDB. Available since version 2.1, it is an easier alternative to MapReduce. Of course, it has some quirks of its own, but I’ll get to that later.

Basic Concept

The underlying concept aggregation framework is this: the documents in your collection pass through the aggregation pipeline. The pipeline is a series of operations that are performed on the documents in the sequence they are defined. The idea is borrowed from the pipes (|) operator in UNIX shell programming. The result of one operation in the pipeline is fed into the next one as input. An operation is defined through expressions. An expression specifies the transformation that is to be applied on the input document. Expressions are generally stateless, they don’t store an information of the documents they process. However there is a special kind of expression known as accumulators, who preserve the state.

Web Analytics using Aggregation Framework

Now that we are familiar with the theories, it’s time to see the framework in action by using it to solve a real world problem. Web analytics seems like a good candidate. If your are logging the traffic to your website in MongoDB, you can run aggregation queries on the data to measure key metrics (most popular webpage, the busiest day in month etc.).

I’ve setup a GitHub repo with the sample code and examples used in this blog post, in case the code is difficult read on this site.

 Populating sample Data

I wrote a script to generate some 1000 dummy documents into a MongoDB database. Here’s what a document looks like:

  "page" : "/2011/01/02/blog-stats-2010/",
  "visited_at" : ISODate("2012-12-11T10:04:28Z"),
  "user_agent" : "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1",
  "ip_address" : "",
  "response_time_ms" : 194.53

Each document represents a page visit by  user on the site. The page field is the link of the webpage visited, visited_at is the time of visit, user_agent is the value of User Agent string of whatever browser/device the user used when seeing the page, ip_address is the IP address of the user, and finally response_time_ms is the time (in milliseconds) the web server took to serve the page. Assuming you are running the MongoDB server on your machine (on localhost, port 27017), you can load the sample data by running the script in mongo client:

$mongo localhost:27017/mysampledb --quite /path/to/load_data.js

If the script finishes without any glitch, you should have a collection web_traffic with 1000 documents in the database mysampledb.

Calculating total visits per day

The following example shows how to calculate the total number of visits on the website for the month of December, 2013.

    $match: {visited_at: {$gte: new Date(2013, 11, 1), $lt: new Date(2014, 0, 1)}}
    $project: { _id: 0, day_of_month: {$dayOfMonth: "$visited_at"}}
    $group: { _id: {day_of_month: "$day_of_month"}, hits: {$sum: 1}}
    $sort: {hits: -1}

Let’s examine the pipeline one operation at a time.

  1. The first operation in the pipeline is $match, it selects the documents whose visited_on values are between December 1st to December 31st 2013.
  2. Next we have $project which reshapes the documents in the stream by adding, removing or changing one or more fields. In this case, we remove the _id field by setting it’s value to zero (_id is added by default so we have to remove it explicitly. The other fields are removed automatically if we don’t add them). We also add a new field day_of_month, which is the month property of visited_on. The month is extracted by using the $dayOfMonth expression.
  3. The $group operator groups documents together and calculates aggregated values. $group must be supplied a value for the _id field, this is expression the documents are going to be grouped by. In our example, we are grouping by day_of_month, the field added by the preceding $project operator. The $sum expression is used to keep a counter, named hits, for every day_of_month seen. In SQL, you could express this as: SELECT COUNT(*) as hits FROM web_traffic GROUP BY MONTH(visited_on).
  4.  Finally $sort orders the grouped documents based on hits in descending order (-1 means descending while 1 means ascending).

The output of the operation is like this:

   "result" : [
     "_id" : {
       "day_of_month" : 7
     "hits" : 40
     "_id" : {
       "day_of_month" : 16
     "hits" : 39
     "_id" : {
       "day_of_month" : 20
     "hits" : 23
 "ok" : 1

The result shows us December 7th was the busiest day of the month (40 page views), whereas December 20 has been least busy (23 page views).

Calculating average, maximum and minimum response times

This next example calculated average, maximum and minimum values of the page response times (response_time_ms).

    avg_response_time_ms: {$avg: "$response_time_ms"},
    max_response_time_ms: {$max: "$response_time_ms"},
    min_response_time_ms: {$min: "$response_time_ms"}
    _id: 0,
    avg_response_time_s: {$divide: ["$avg_response_time_ms", 1000]},
    max_response_time_s: {$divide: ["$max_response_time_ms", 1000]},
    min_response_time_s: {$divide: ["$min_response_time_ms", 1000]}

Let’s quickly go through the operations in the pipeline:

  1. The first is a $group where we set the _id to null. This means we are not grouping by any field. We still have to calculate the average, maximum and minimum values of response times and we are doing that by applying $avg, $max and $min on response_time_ms field.
  2. The project operation suppresses the _id field, and at the same time divides the values by 1000 (with the $devide expression) to transforms the millisecond values into second.

Finding usage share of visitors’ browsers

In this example we will find out the unique browsers and platforms used by the site’s visitors using the User Agent value and calculate their percentage share.

var total = db.web_traffic.find({user_agent: {$exists:true}}).count();
var pipeline = [
    $group: {_id: "$user_agent", count: {$sum: 1}}
    $project: {percentage: {$multiply: ["$count", 100 / total]}}
    $sort: {percentage: -1}
  1. First we find the total number of documents that have the user_agent field  populated, store the number as total.
  2. The $group in the pipeline groups the documents based on user_agent field (_id: $user_agent) and counting their numbers (count: {$sum: 1}).
  3. The $project calculates the percentage by diving count with total and multiplying with 100.
  4. The $sort sorts the result by percentage in descending order.

Finding weekly visit patterns of users

The aggregation pipeline in this example calculates how many times a user visits the website per weekday and what pages does he read. The user is represented by ip_address in this case. In real life, websites have more sophisticated methods for tracking unique users.

    $project: {
      _id: 0,
      page: 1,
      ip_address: 1,
      visited_weekday: {$dayOfWeek: "$visited_at"}
    $group: {
      _id: {visited_weekday: "$visited_weekday", ip_address: "$ip_address"},
      visits: {$sum: 1},
      pages_visited: {$addToSet: "$page"}
    $sort: {"_id.visited_weekday": 1}
  1. $project outputs documents with fields page, ip_address and calculated on named visited_weekday which is the day of week (1 is Sunday, 2 is Monday and so on) in visited_at timestamp.
  2. The documents are grouped on visited_weekday and ip_address, the total visits per IP is counted by $sum. Also, the value of page field is added to an array pages_visited by the expression $addToSet.
  3. Sort the documents on visited_weekday in ascending order.

The result of this aggregation looks like this:

  "result" : [
       "_id" : {
       "visited_weekday" : 1,
       "ip_address" : ""
     "visits" : 19,
     "pages_visited" : [

The first entry in the result set shows user with IP address visited the site 19 times on Sunday (weekday 1) and visited the links in the pages_visited array.

Calculating duration of users’ visits on the website

In this last example, we will use a pipeline that calculates how much time (in hours) each user have spent on the site on December 7, 2013.

    $match: {visited_at: {$gte: new Date(2013, 11, 7),
    $lt: new Date(2013, 11, 8)}}
    $sort: {visited_at: 1}
    $group: {
      _id: "$ip_address",
      first_visit: {$first: "$visited_at"},
      last_visit: {$last: "$visited_at"},
      total_visits: {$sum: 1}
    $match: {
      total_visits: {$gt: 1}
    $project: {
      duration_hours: {$subtract: [{$hour: "$last_visit"}, {$hour: "$first_visit"}]}
    $sort: {duration_hours: -1}
  1. First in the pipeline is a $match which selects the documents with visited_at on December 7 2013.
  2. Next, $sort sorts the matched documents on the timestamp in ascending order.
  3. $group groups the document on ip_address and counts total visits per IP address. It also save the first and the last value of visited_at for each group.
  4. The next $match gets filters out the documents with total_visit of 1 or less.
  5. $project calculates the duration of user’s visit by subtracting the first value of visited_at from the last value and expressing it in hours.
  6. Finally sorting the documents on duration in descending order.


There are some limitations of the framework that you should be aware of:

  • The final output of the aggregation pipeline is stored in a single document in memory. This is in contrast with MapReduce which allows you store the result persistently in a collection. This means the size of the aggregation result should exceed the MongoDB document size limit, which is currently 16 megabytes.
  • If the operation consumes more the 10% of system RAM, it produces an error.
  • Aggregation pipeline cannot operate on these data types: Symbol, MinKey, MaxKey, DBRef, Code, CodeWScope.

Recommended Reading

Stories to read over the weekend

It’s been a while (1 year, 3 months, 23 days to be exact) since I last blogged. I apologize to the only reader of this blog, myself, for this insincerity on my part. I blame the micro-blogging platform that I have been using to express myself within 140 characters (and I am not very regular at that as well) for this laziness.

Blogging regularly is hard. It takes quite a lot of creative discipline, not to mention you have to find something that you would like to write about. Matthew Inman made a really funny comic about the same problem on his website, The Oatmeal. I can’t seem to find it (and I just spent half an hour reading other funny posts there. Creative discipline my a**).

Anyways, I have decided to blog at least once a week from now on. And the easiest way to do that is sharing what I have read over the week. One of the few good things about Twitter is that you get to read what other people write and share. So every week I am going to summarize and share some interesting posts I have read, same way superstar tech blogger Om Malik does on his blog Gigaom.

I have no such illusion that I have a following as massive as Om’s. But I am going to do it anyway, because, it is going to keep me to my promise of one post per week. And more importantly, summarizing and sharing works of others is a great creative exercise. So without further ado, here’s the list of interesting stories I’ve read this week:

1. What is graphene? Here’s what you need to know about a material that could be the next silicon (Science) – Graphene, the wonder material of the 21st century is believed to replace silicon in electronic devices in the upcoming decade. This article explains what makes graphene so special and what challenges do we currently face in producing/exploiting it.

2. Why Microsoft’s reorganization is a bad idea (Tech/Business) – The software giant went through a structural reorganization. The author makes an argument why divisional organization (structuring the company around products) is better for a large corporation than functional organization (arranging the company around specific roles), and why it is a bad bet by Steve Ballmar choosing the later for Microsoft.

3. Entropy Crushers (Startups/Business) – When your startup of handful of people grows larger into a company employing hundreds, what do you do to ensure that communication is clear and things get done with the least bureaucratic overhead? This article made me change my view of project management and what a project manager is supposed to do.

4. Rise of a Bangladeshi Entrepreneur at US (Entrepreneurship) – A feel good story of a Bangladeshi making in big in the US. An engineer by training, Mahfuz founded his startup DISYS while working at his day job at Mobil. 19 years since its start, the company is very profitable and looking into going public by 2017.

5. Sunshine on His Shoulders (Biography) – A biographical article on Professor Dwijen Sharma, the leading botanist and philosopher of the country. Professor Sharma was in the faculty of Notre Dame College in Dhaka. He had long left when I enrolled in. But walking around the beautiful campus of Notre Dame, you had to appreciate the genius of his landscape designing. Fascinating read about the life of a man, whom I feel, has not been highlighted enough in the media.

TAB completion for fabric tasks [on OS X]

Found an excellent bash script on foobar.lu that enables tab completion on the fabric tasks defined in fabfile.py script (in case you don’t know what Fabric is, try Yuji Tomita’s article to get started with it). I just had to modify a little bit to make it work on OS X. I actually wanted to post it in their comments section, but it seems the comments are blocked on that site. So here it goes:

Install bash-completion with Homebrew

brew install bash-completion

You’ll need to add some lines in your ~/.bash_profile file to finish the installation. This will create an etc/bash_completion file under /usr/local directory. Now open the ~/.bash_profile file and add the following lines at the end:

function _fab_complete() {
    local cur
    if [ -f "fabfile.py" ]; then
        COMPREPLY=( $(compgen -W "$(fab -F short -l)" -- ${cur}) )
        return 0
        # no fabfile.py found. Don't do anything.        
        return 1
if [ -f /usr/local/etc/bash_completion ] && ! shopt -oq posix; then
    . /usr/local/etc/bash_completion
    complete -o nospace -F _fab_complete fab

Reload the file with source ~/.bash_profile command, navigate to your project directory where your Fabric script is located and try it out yourself.

Giveaway Contest : PHP and MongoDB Web Development Beginner’s Guide

I’m happy to announce that Packt Publishing has arranged a giveaway contest for the book PHP & MongoDB Web Development: Beginner’s Guide. All you have to do is participate in a small programming challenge. The winners of the contest will be receive a copy of the book each, free of charge!

The challenge is to build a standalone, re-useable HTTP session manager using PHP and MongoDB.

The details of the contest are available here.

We hope that this contest will spark your interest in building web apps using PHP and MongoDB. Happy Coding!

PHP and MongoDB Web Development Beginner’s Guide – Thoughts of a first-time author

PHP and MongoDB web development

Social networking doesn’t always make you procrastinate, sometimes it pays off! When @packtauthors tweeted that they were looking for someone to author a book on PHP and MongoDB, I made contact. Few weeks later I signed a contract for writing the book. And six months after that, I am pleased to announce that PHP and MongoDB Web Development Beginner’s Guide is published and out for sale!

In this post I intend to share a few words about the motivation behind the book and the journey of a first time author.

The Motivation

I’m a supporter of the idea the MongoDB can potentially be the new M in LAMP. The web application data storage requirements have changed a lot during the past 4-5 years. Instead of producing contents of their own, the most popular websites are hosting contents created by their users. These contents are diverse in nature and humongous in volume. Mapping the diverse data into a rigid data structure gets harder as the volume grows. This is where the ‘Flexible Schema’ nature of MongoDB fits really well. Also MongoDB is easy to learn, developers with relational database experience should find little trouble adapting to it. There is a lot of similarity between the underlying concepts of an RDBMS and MongoDB (think documents for rows, and collections for tables). Developers don’t need to wrestle with radical ideas such as column-oriented or graph theory based data structures as some other NoSQL databases require them to. Finally, it is open-source, freely available (Creative Commons License), supports multiple platforms (Windows/Linux/OS X), have great documentation and a very co-operative community, and plays nicely with PHP! All these have lead me to believe that in near future MongoDB will be where MySQL is right now, the de facto database for web application development (I would urge you to read Stephen O’Grady’s article which makes more persuasive arguments). And since PHP is the dominating language for web programming, writing a book on web development with PHP and MongoDB felt just right.

The intended audience for this book are web developers who are completely new to MongoDB. It focuses on application development with PHP and MongoDB rather than focusing only on MongoDB. The first few chapters will try to ease the reader into understanding MongoDB by building a simple web application (a blog) and handling HTTP sessions with MongoDB as the data back-end. In the next chapters he will learn to solve ‘interesting’ problems, such as storing real-time web analytics, hosting and serving media content from GridFS, use geospatial indexing to build location-aware web apps. He will also brainstorm about scenarios where MongoDB and MySQL can be used together as a hybrid data back-end.

The Inspiration

Scott Adams, the creator of the famous Dilbert comic strip, wrote an inspirational article on Wall Street Journal. I’m going to quote a few lines here:

“I succeeded as a cartoonist with negligible art talent, some basic writing skills, an ordinary sense of humor and a bit of experience in the business world. The ‘Dilbert’ comic is a combination of all four skills. The world has plenty of better artists, smarter writers, funnier humorists and more experienced business people. The rare part is that each of those modest skills is collected in one person. That’s how value is created.”

These words moved me. I like programming and I like writing, and although there are smarter programmers and better writers out there, by combining these two passions I could potentially produce something. Besides I had an amazing learning experience with MongoDB. I built an API analytics solution with MySQL which became difficult to handle as the volume of the data grew. I started playing with MongoDB as a potential alternative. A month later I moved the entire data from MySQL to a more solid and scalable solution based on MongoDB. I wanted to share this learning experience through a series of blog posts but lacked the personal discipline and commitment to do so. Being obligated a deliver a book within tight deadlines solved that problem!

I also must thank Nurul Ferdous, my friend and former colleague who is a published tech author himself. His guidance and influence has been instrumental.

The Journey

My journey as an author writing a book for the first time has been an exhaustive yet amazing one! I work in a tech startup, which naturally requires longer than usual hours and harder than usual problems to solve. I would come home late and tired, research on MongoDB topics, plan how to deliver the message to the reader, write code, test and debug the code, write the content on a text editor, fight with Microsoft Word so the content has proper formatting as required by the publisher. Then on weekends I would revise and rewrite most of what I have done over the week and hustle to make the deadline. Nevertheless it all had been a rewarding experience.

In the rewrite phase I had a lot of help from the technical reviewers – Sam Millman, Sigert De Vries, Vidyasagar N V and Nurul Ferdous. They corrected my errors, showed me what more could be added to the content and what should be gotten rid off, helped me communicate complicated topics to readers in a clearer way. I convey my sincere appreciations to them!

Time to end this lengthy blog post. I hope you find this book enjoyable and use it to build some really cool PHP-MongoDB apps! I will then consider my endeavor to be a success.

Random snaps from Thailand tour

I’m kinda bummed out since I didn’t get any chance to travel this year (and it looks like I won’t for the rest of the year). So I’ve decided to share some of the photos that I took in my Thailand tour last year. This photos have been lying around in my hard drive for almost a year , so I finally decided to upload a few of them.

This picture was taken on a beach in Phuket, Can’t remember the name of the beach right now.

The rock at James Bond Island, named so because it appeared in one of the James Bond movie.

You are always reflective when you are on a canoe.

A colorful moment.

This baby elephant put on quite a good show.


My attempt at snorkeling.

phi phi island

A sunny day on the beach of Koh Phi Phi

loh dalum bay

Loh Dalum bay

Learn core Python from Stackoverflow

The other day I needed to brush up my knowledge on Python decorators, for implementing a profiling hook for a Django REST API I’ve been working on. I googled around and landed on a question titled Understanding Python Decorators on Stackoverflow.com. The answer given by the user e-satis is an excellent introduction to decorators in Python, although it has not been selected as the official answer. Go ahead an give it read if you have done some Python coding.

This got me thinking. This guy does not care about whether or not his answer gets selected before others (so that he can bag some reputation). He took his time and explained what decorators are in a well thought-out, step-by-step manner. The end result is an answer worthy of being placed in a beginner level Python book as a chapter on decorators! So there must be other answers as awesome as this one, given by users as knowledgable as e-satis! I set out to find few more great StackOverflow threads on core Python programming, had them bookmarked for future reads, and now sharing them on this blog post. You should read each of them at least once to make your knowledge on core Python more solid.

Understanding Python decorators

As I mentioned above, great introduction to decorators in Python.

What is a meta-class in Python

Another great answer from e-satis (later turned into a community wiki). Explains what meta-classes are in Python and why are they so useful.

How to sort a list of objects in Python, based on an attribute of the objects?

The answer to this question often comes in handy!

Understanding Python super() and init methods

A short yet useful answer explaining what good is super() for. You should also read the article Pythons’s super() considered super! along with this.

What is the relationship between __getattr__ and getattr?

I always wondered; and Kimvais provided the answer! Also checkout Alex’s answer in the same thread.

The Python yield keyword explained

Another gem from e-satis. Introduced the concept of iterators and generators in Python and goes on to explain the use of yield statement.

Single quotes vs. double quotes in Python

The stylistic reasons for choosing double quotes or single quotes when coding in Python. Worth a read.

Python Compilation/Interpretation process

Very detailed answer explaining Python compilation/interpretation process to programmers not coming comp-sci background; something every Pythonist should know.

Python progression path- from apprentice to guru

Last but not the least! A great thread showing what road a Python beginner should take to achieve mastery.

If you know about any other great StackOverflow posts, please do share them on the comment section. I’ll update my list. The posts must be about Python (core Python more specifically).