在使用mongodb的mapreduce時,需要注意以下2點:
1.map中的emit的第二個參數和reduce返回的數據格式應該是一致的,否則會出現難以預見到的錯誤!
2.reduce方法是被迭代調用的,同一個key也會被調用多次,所以計算和時不能根據vals.length計算,而應該是累加和!
代碼:
m = function(){emit(this.info.level+"_"+this.info.mType,{level:this.info.level,mType:this.info.mType, title:this.info.headship, count:1});}
r = function(k, vals){var m={level:vals[0].level,mType:vals[0].mType,title:vals[0].title,count:0};for(var i in vals)m.count+= vals[i].count; return m;}