我正在尝试在我们的应用程序中汇总一堆用户个人资料数据。每个用户都有一个带有性别和种族属性的嵌入式配置文件。
{
'email': 'foo@email.com',
'profile': {
'gender': 'male',
'ethnicity': 'Hispanic'
}
}
如果我使用这样的组功能:
db.respondents.group({
key: {},
initial: {'gender': {'male':0,'female':0}, 'ethnicity': {}, 'count': 0},
reduce: function (user, totals) {
var profile = user.profile;
totals.gender[profile.gender]++;
totals.ethnicity[profile.ethnicity] = (totals.ethnicity[profile.ethnicity] || 0);
totals.ethnicity[profile.ethnicity]++
totals.count++;
}
});
我以我想要的形式得到结果:
{
"gender" : {
"male" : ###,
"female" : ###
},
"ethnicity" : {
"Caucasian/White" : ###,
"Hispanic" : ###,
...
},
"count" : ###
}
我无法让它作为 map/reduce 命令工作,当然使用不同的 reduce 函数。我不确定如何使总数相加。他们总是不正确的。我知道reduce的输出必须与map的输入格式相同,但我觉得我在reduce工作的方式上遗漏了一些东西......
作为对@Jenna 的回应,输入如下所示:
{
'email': 'foo@email.com',
'profile': {
'gender': 'male',
'ethnicity': 'Hispanic'
}
}
功能是:
function map(){
emit('demographics', this.profile)
}
function reduce (key, values) {
var reduced = {'gender': {'male':0,'female':0}, 'ethnicity': {}, 'count': 0};
values.forEach(function(value) {
reduced.gender[value.gender]++;
reduced['ethnicity'][value.ethnicity] = (reduced['ethnicity'][value.ethnicity] || 0);
reduced['ethnicity'][value.ethnicity]++;
reduced.count++;
});
return reduced;
}
输出是:
{
"_id": "demographics",
"value": {
"gender": {
"male": 76.0,
"female": 64.0
},
"ethnicity": {
"Caucasian/White": 109.0,
"Other": 5.0,
"Asian": 10.0,
"African-American": 8.0,
"Hispanic": 7.0,
"Native American": 1.0
},
"count": 141.0
}
}
输出不正确,因为数据库中有超过 100k 条记录。