Kaliyug Antagonist
Kaliyug Antagonist

Reputation: 3612

Mongo DB mapreduce confusion

I have a collection with records as given below :

{ "_id" : "279771168740729_100208116788436_242", "user_likes" : false, "message" : "nice work,nice bank", "like_count" : 4, "page_username" : "icicibank", "page_id" : "279771168740729", "can_remove" : false, "from" : { "id" : "100003762913358", "name" : "Ramakant Mirewad" }, "page_name" : "ICICI Bank", "post_id" : "279771168740729_100208116788436", "created_time" : "2012-06-06T15:40:33+0000" }
{ "_id" : "279771168740729_100208116788436_250", "user_likes" : false, "message" : "Best bank of india", "like_count" : 4, "page_username" : "icicibank", "page_id" : "279771168740729", "can_remove" : false, "from" : { "id" : "100003520362950", "name" : "Santosh Pandey" }, "page_name" : "ICICI Bank", "post_id" : "279771168740729_100208116788436", "created_time" : "2012-06-06T15:48:45+0000" }

My objective is to count the occurrence of the keyword "Best" in a message. Here, message can contain only "Best" or can contain sentences having "Best". Accordingly, I wrote the following :

var mapFunction = function() {

    var keyword = "Best";
    var messageStr = this.message;

    if(messageStr.indexOf(keyword) != -1){
    emit(keyword, 1);
    }

};

var reduceFuntion = function(keyword, keywordCountCollection) {

    return Array.sum(keywordCountCollection);
};


db.icici_facebook.mapReduce( mapFunction,reduceFuntion,{out : "icici_fb_keyword_count", verbose : true})

I got an error :

Sat Aug 17 12:10:25.362 JavaScript execution failed: map reduce failed:{
        "errmsg" : "exception: JavaScript execution failed: TypeError: Cannot ca
ll method 'indexOf' of undefined near 'essageStr.indexOf(keyword) != -1)'  (line
 6)",
        "code" : 16722,
        "ok" : 0
} at src/mongo/shell/collection.js:L970

I tried match() etc. too but I guess I'm missing something because of which the js functions are not getting recognized - how should I proceed?

Upvotes: 2

Views: 1376

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

Your problem is purely java script code, or the fact that you don't check if your documents contain a message field:

if(messageStr.indexOf(keyword) != -1){
    emit(keyword, 1);
}

should be

if(messageStr  !=  null && messageStr.indexOf(keyword) != -1){
    emit(keyword, 1);
}

Anyway, your goal is much simpler with a query:

db.icici_facebook.count({message : /best/i})

Upvotes: 2

Related Questions