如何在mongodb文档中迭代对象?
我的mongo收藏中的文档如下所示:如何在mongodb文档中迭代对象?,mongodb,loops,mapreduce,Mongodb,Loops,Mapreduce,我的mongo收藏中的文档如下所示: { "_id" : ObjectId("568f7e67676b4ddf133999e8"), "auth_dic" : { "2406" : [ "44735" ], "6410" : [ "223423" ] ... ... }, "user_id" : "fdasd2342
{
"_id" : ObjectId("568f7e67676b4ddf133999e8"),
"auth_dic" : {
"2406" : [
"44735"
],
"6410" : [
"223423"
]
...
...
},
"user_id" : "fdasd23423"
}
这是一个用户,在“auth_dic”中有许多类似于“2406”“6410”的id
我想使用用户映射减少方法来统计有多少用户拥有“2406”、有多少用户拥有“6410”和其他类型。
我的绘图程序是:
mapper = Code('''
function(){
this.auth_dic.forEach(function(app_id){
emit(app_id, 1);
});
}
''')
我的减速机是:
reducer = Code('''
function(key, values){
var total = 0;
for (var i = 0; i < values.length; i++) {
total += values[i];
}
return total;
}
''')
reducer=代码(“”)
功能(键、值){
var合计=0;
对于(变量i=0;i
但是映射程序无法工作,因为函数“forEach”无法让用户迭代dic,我可以做些什么来解决此问题?运行以下MapReduce操作:
mr = db.runCommand({
"mapreduce" : "collectionName",
"map" : function() {
var map = this.auth_dic;
for (var key in map) {
if (map.hasOwnProperty(key)) { emit(key, 1); }
}
},
"reduce" : function(key, val) { return Array.sum(val); },
"out": "collectionName" + "_keys"
})
然后查询结果集合,以查找动态键的所有计数:
db[mr.result].find()
你应该考虑改变你的文档结构,并使<代码> AuthyDic 一个子文档数组。通常,现在添加HasObjor属性是一个好主意,否则你可能会从原型中重复关键字。