2013-08-17 151 views
2

我有記錄的集合,如下所示:蒙戈DB MapReduce的混亂

{ "_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" } 

我的目標是計算一個消息關鍵字「最佳」的發生。在這裏,消息可以只包含「最好」或可以包含具有「最佳」的句子。因此,我寫了下面:

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}) 

我得到了一個錯誤:

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 

我試圖匹配()等太多,但我想我失去了一些東西,因爲它的JS功能都沒有得到承認 - 我應該如何繼續?

回答

2

你的問題是純粹的Java腳本代碼,或事實上你不檢查,如果你的文檔包含一個消息字段:

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

應該

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

無論如何,你的目標是更簡單的查詢:

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

+0

它的工作,但只是爲了確認 - 是錯誤的,因爲在某些文檔中,消息不存在?或者是其他東西?我仍然不清楚我犯了什麼js錯誤 –

+1

是的,錯誤是由於你的一些文檔缺少消息字段,你不能在null/undefined處調用indexOf –