Question

I am currently using MongoDB's MapReduce to generate hourly ad view counts like this:

{ _id : "4/1/2011 9:00 AM", value : { AdViews_Total : 4 } }

This works fine, and I get the results in a collection that I can subsequently query much more quickly than the original data. Now, what I'd like to do is something like this:

{ _id : "4/1/2011 9:00 AM", value : { ByBrowser : { "Internet Explorer" : 4, "FireFox" : 4 } } }

To do that, I think I'd need to be able to merge two or more disjoint documents in my Reduce operation, for example:

{ _id : "4/1/2011 9:00 AM", value : { ByBrowser : { "FireFox" : 3 } } }
{ _id : "4/1/2011 9:00 AM", value : { ByBrowser : { "FireFox" : 1 } } }
{ _id : "4/1/2011 9:00 AM", value : { ByBrowser : { "Internet Explorer" : 4 } } }

Does anyone know what such a Reduce operation might look like, keeping in mind that the browser names are not known ahead of time?

Was it helpful?

Solution

I have managed to achieve what I am after using the following, though I suspect that there might be a more efficient way of doing it. I'll leave this up for a day before marking as answer...

function Reduce(key, arr_values) {
    var reduced = { 
        AdViews_Total : 0, 
        DefaultAdViews_Total : 0, 
        Sessions_Total : 0,
        Browsers : [ ],
        }; //a document
    for(var i in arr_values) {
        reduced.AdViews_Total += isNaN(arr_values[i].AdViews_Total) ? 0 : arr_values[i].AdViews_Total;
        reduced.DefaultAdViews_Total += isNaN(arr_values[i].DefaultAdViews_Total) ? 0 : arr_values[i].DefaultAdViews_Total;
        reduced.Sessions_Total += isNaN(arr_values[i].Sessions_Total) ? 0 : arr_values[i].Sessions_Total;
        if (null != arr_values[i].Browsers)
            for (var j in arr_values[i].Browsers)
            {
                var browser = arr_values[i].Browsers[j]
                var browserLabel = browser.Browser;
                var browserCount = browser.Count;
                var browserFound = false;
                for (var k in reduced.Browsers)
                {
                    if (reduced.Browsers[k].Browser == browserLabel)
                    {
                        reduced.Browsers[k].Count += browserCount;
                        browserFound = true;
                    }
                }
                if (!browserFound)
                    reduced.Browsers[0] = browser;
            }
    }
    return reduced;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top