2012-03-10 41 views
0

我有一個關於Map/Reduce在mongodb中排序內部文檔的問題。 的方案是像以下:映射/減少和排序嵌套文檔

{ 
    "_id" : 16, 
    "days" : { 
     "1" : 123, 
     "2" : 129, 
     "3" : 140, 
     "4" : 56, 
     "5" : 57, 
     "6" : 69, 
     "7" : 80 
} 

所以我現在的問題是: 我如何能實現從上面的數據總結了一些特定的日子。 舉例:

我想總結第1,3和7天的值,並從中得出結果。 我試過 MapReduce aggregation based on attributes contained outside of document的解決方案,但沒有取得任何成功。

任何人都可以幫助我嗎?

回答

3

MapReduce是一個循環操作一堆文件並執行操作的操作。我不完全確定這正是你想要的,但可能你發佈了一個更簡單的問題形式。在任何情況下,以下代碼通過爲單個文檔發射3次,使用文檔的_id作爲reduce函數的關鍵字。

doc = {_id : 16, days : { 1 : 123, 2 : 129, 3 : 140, 4 : 56, 5 : 57, 6 : 69, 7 : 80 }}; 
db.so.insert(doc); 

map = function() { 
    emit(this._id, this.days["1"]); 
    emit(this._id, this.days["3"]); 
    emit(this._id, this.days["7"]); 
} 

reduce = function (k, vals) { 
    var sum = 0; 
    vals.forEach(function (v) {sum += v;}); 
    return sum; 
} 

res = db.so.mapReduce(map, reduce, {out : {inline : 1}}); 
res.find(); 
+0

感謝您的回答。但是,當我嘗試這個我有一個編譯錯誤。我認爲蒙戈不喜歡「this.days.1」 – MadeOfSport 2012-03-10 13:17:17

+1

對不起,我修好了。將錯誤的版本粘貼到答案中!可能你找到答案很難找到你自己的原因是this.days.1不起作用,但this.days [「1」]。 – 2012-03-10 21:18:27