问题描述
当我检查它是否按预期工作时,我写了几个月的map-reduce函数。 现在,我试图用相似的数据运行相同的功能,并获得奇怪的结果。
我已经在此模拟器中测试了旧代码:http://targetprocess.github.io/mongo-mapreduce-debug-online/ 并按我的预期工作。
有地图功能:
map(){
const report = {
clicks: 1
};
const baseKey = {date: this.date}
const attrs = ['country']
attrs.forEach(attr => {
let docKey = { ...baseKey,extId: this.extId,attr };
emit(docKey,{ report,attrValue: this[attr]})
})
}
示例文档:
{
"_id" : ObjectId("5f86b5c240d9925e4ccab199"),"extId" : ObjectId("5f8475154f8ee65494e5320a"),"country" : "DE","date" : ISODate("2020-10-14T00:00:00Z"),"time" : ISODate("2020-10-14T08:24:34.649Z"),"__v" : 0
}
我尝试了最简单的reduce函数:
reduce(key,values){
return 1
}
我应该得到:
{
"_id": {
"date": "2020-10-14T00:00:00.000Z","extId": "5f8475154f8ee65494e5320a","attr": "country",},"value": 1
}
但是我得到了:
{
"_id" : {
"date" : ISODate("2020-10-14T00:00:00Z"),"table" : ObjectId("5f8475314f8ee65494e5320b"),"attr" : "country"
},"value" : {
"report" : {
"clicks" : 1,"attrValue" : "DE"
}
}
看起来它从发射返回值,并且 我找不到未能返回应有的1的任何原因。
编辑:我发现当我提供给mapReduce的查询与1个文档匹配时会发生这种情况(即使map函数发出不止一次)。包含多个文档时,它将按预期工作。
我该如何解决?
解决方法
如果某个键只有1个值,MongoDB将跳过reduce函数。 显然我在reduce函数中做了一些映射,这是错误的。 我更改了映射的输出以匹配reduce输出的结构,它的工作与预期的一样。