mongodb映射reduce返回错误的值



几个月前我写了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函数发出不止一次(。当它有多个文档时,它会按预期工作。

我该如何解决?

MongoDB如果某个键只有1个值,则跳过reduce函数。显然我在reduce函数中做了一些映射,这是错误的。我更改了映射的输出以匹配reduce输出的结构,它的工作方式与预期的一样。

这非常有帮助:https://stackoverflow.com/a/22095649/9103301

最新更新