Mongo map reduce with Node.js

You’re running Node.js and using mongodb and you need to run a map / reduce.  In this example we will run a map / reduce that:

  • emits items that were created within the past 30 days.  We use our own ‘timestamp’ field for this, not _id.
  • merge the results with anything that was already existing from prior m / r’s

Here’s the code:

// set up the query so it runs for calls from last 30 days
var query = { $where: 'this.timestamp >  (new Date().getTime() - (1000 * 60 * 60 * 24 * 30))  ' };

// set up the output so that it overwrites what's in the coll for days that already exist
var out = { merge : "restCallReduction" };

var map = function() {
    if (!this.entityIds) {
        return;
    }
    for (index in this.entityIds) {
        var callDate = new Date(this._id.getTimestamp());
        // We only care about unique days so set all else to 0
        callDate.setMinutes(0);
        callDate.setHours(0);
        callDate.setMilliseconds(0);
        callDate.setSeconds(0);
        var zcredits = 0;
        if (!(typeof this.credits === undefined)) {
            if (this.credits > 0) {
            zcredits = 1;    
        }    
        emit({a: this.appId, d: callDate.getTime(), t: this.entityIds[index] }, { "count" : 1, "credits" : zcredits } );
    }
}};

var reduce = function(key, values) {
    var result = { count: 0, credits: 0 };
    values.forEach(function(value) {
        result.count += value.count;
        result.credits += value.credits;
    });
    return result;
};

var result = db.runCommand({
... "mapreduce" : "restCall",
... "map" : map,
... "reduce" : reduce,
... "query" : query,
... "out" : out});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s