2011-03-23 65 views
1

鉴于这样的文件:的MongoDB的Map/Reduce斗争

{ "_id": { 
    "$oid": "4d88ca367d190a0aa4e27806" }, "Rows": [ 
    { 
     "Columns": { 
     "Date": "Tue, 02 Aug 2011 00:00:00 GMT -04:00", 
     "Col2": 33 
     "Col3": 44 
     } 
    }, 
    { 
     "Columns": { 
     "Date": "Mon, 17 Oct 2011 00:00:00 GMT -04:00", 
     "Col2": 55 
     "Col3": 66 
     } 
    } ], "DocName": "For My Eyes Only", "DocIdentifier": 3322445 } 

及以下的Map/Reduce函数:

function() { 
    this.Rows.forEach(function(bulkcol) { 
    emit(this.DocName, { TrendValue: bulkcol.Columns.Col2 }); 
    }); 
}; 

function(key, values) { 
    var sum = 0; 
    values.forEach(function(currTrend) { 
    sum += currTrend.TrendValue; 
    }); 
    return {DocName: key, TrendValue: sum}; 
}; 

我得到以下输出:

{ 
    "_id": null, 
    "value": { 
    "DocName": null, 
    "TrendValue": 88 
    } 
} 

为什么是DocName null?

+0

链接就此问题向同样在MongoDB论坛上:http://groups.google.com/group/mongodb-user/browse_thread/thread/44219c4994e51476 – AdaTheDev 2011-03-24 13:31:57

回答

0

如果我在看这个权利,我想我认为,这个在emit函数中并不是你期望的那样。

由于它在函数内部,所以这个引用了每一行,而不是父文档。试试这个:

function() { 
    this = parent; 
    this.Rows.forEach(function(bulkcol) { 
    emit(parent.DocName, { TrendValue: bulkcol.Columns.Col2 }); 
    }); 
}; 
+0

你是不是指'var parent = this;'?那也行不通。它把我的TrendValue也设为0! – ForeverLearning 2011-03-23 20:32:37

+0

这就是我的意思,是的。看看Kyle Banker的博客,他在mongo的map/reduce上有非常好的博客文章。我敢打赌,这是你错过的一件小事。 – 2011-03-23 20:36:43

+0

关于Map/Reduce的事情无论我在哪里阅读的博客和文章总是有一些愚蠢的语法情况没有被覆盖到任何地方。尽管我读过银行家的博客。 – ForeverLearning 2011-03-23 20:39:04

1

问题是非常像Srdjan指出的 - 在你的forEach函数中,你实际上并没有对父文档的引用。

如果您改变了地图功能,这一点,它的工作原理:

m = function() { 
    var docName = this.DocName; 
    this.Rows.forEach(function(bulkcol) { 
    emit(docName, { TrendValue: bulkcol.Columns.Col2 }); 
    }); 
}; 

因此,分配文档名称进入循环前一个变量,然后使用中它

+0

如果你可以帮助,感激..http://stackoverflow.com/questions/35426213/how-to-group-mongodb-mapreduce-output – user29578 2016-02-16 09:33:56