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" : "23.22.63.122",
  "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.

db.web_traffic.aggregate(
[
  {
    $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).

db.web_traffic.aggregate([
{
  $group:{
    _id:null,
    avg_response_time_ms: {$avg: "$response_time_ms"},
    max_response_time_ms: {$max: "$response_time_ms"},
    min_response_time_ms: {$min: "$response_time_ms"}
    }
  },
  {
  $project:{
    _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}
  }
];
db.web_traffic.aggregate(pipeline)
  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.

db.web_traffic.aggregate([
  {
    $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" : "4.242.114.0"
     },
     "visits" : 19,
     "pages_visited" : [
       "/2012/03/26/tab-completion-for-fabric-tasks-on-os-x",
       "/2010/02/05/modifying-pdf-files-with-php",
       "/2011/11/24/random-snaps-from-thailand-tour",
       "/2011/01/29/on-programming-and-craftsmanship",
       "/2011/03/04/getting-started-with-pipvirtualenv",
       "/2010/05/07/moments-from-darjeeling",
       "/2011/01/02/blog-stats-2010/",
       "/2011/05/06/making-chrome-canary-the-default-browser-os-x"
     ]
   }
...

The first entry in the result set shows user with IP address 4.242.114.0 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.

db.web_traffic.aggregate([
  {
    $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.

Limitations

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

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.