views:

8

answers:

0

I have an example to learn map-reduce in mongo, modified from: http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-ShellExample2

// for timestamps
function padZero(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function printLog(l) {
    print(l.ts + ': ' + l.msg);
}

function log(message) {
    d = new Date();
    db.log.save({ ts : d.toTimeString().substring(0, 8) + '.' + padZero(d.getMilliseconds(),3), msg : message});

// populate the collection
db.things.save( { _id : 1, tags : ['1-dog', '2-cat'] } );
db.things.save( { _id : 2, tags : ['3-cat'] } );
db.things.save( { _id : 3, tags : ['4-mouse', '5-cat', '6-dog'] } );
db.things.save( { _id : 4, tags : []  } );
db.things.save( { _id : 5, tags : ['7-mouse', '8-dog', '9-dog'] } );    

// map function
m = function() {
    log('map ' + this.tags);
    this.tags.forEach(function(z) { 
        log('\temit:' + z); 
        emit( z.substring(2) , { count : 1, name : z });
    });
};

// reduce function
r = function( key , values ) { 
    log('reduce ' + key + ' ' + values.length + ' items'); 
    var total = 0; 
    for ( var i=0; i < values.length; i++ ) { 
        log('\tvalue[' + i + '] name:' + values[i].name +' count:' + values[i].count); 
        total += values[i].count; 
    } 

    log('\treturn:' + total); 
    return { count : total, name : key };
};

log('start');
res = db.things.mapReduce(m,r,{scope: {log : log, padZero: padZero}});
log('done');
db[res.result].find();

db.log.find({},{ts:true,msg:true}).forEach(printLog);

In 1.4, I could see logs in the map function. But after 1.6, I can only seethe reduce function logs only. The results are still correct. Do you have any idea? Thanks.