【发布时间】:2021-01-28 19:58:02
【问题描述】:
几个月前我写了 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 mapreduce mongo-shell