【发布时间】:2015-03-24 19:29:54
【问题描述】:
我的 mongoDB 中有 100 个文档,假设每个文档都可能在不同条件下与其他文档重复,例如名字和姓氏、电子邮件和手机。
我正在尝试 mapReduce 这 100 个文档以具有键值对,例如分组。
在数据库中有第 101 条重复记录之前一切正常。
与第 101 条记录重复的其他文档的 mapReduce 结果的输出已损坏。
例如:
我现在正在处理名字和姓氏。
当数据库包含 100 个文档时,我可以得到包含的结果
{
_id: {
firstName: "foo",
lastName: "bar,
},
value: {
count: 20
duplicate: [{
id: ObjectId("/*an object id*/"),
fullName: "foo bar",
DOB: ISODate("2000-01-01T00:00:00.000Z")
},{
id: ObjectId("/*another object id*/"),
fullName: "foo bar",
DOB: ISODate("2000-01-02T00:00:00.000Z")
},...]
},
}
这正是我想要的,但是......
当数据库包含超过100个可能的重复文档时,结果变成了这样,
假设第 101 个文档是
{
firstName: "foo",
lastName: "bar",
email: "foo@bar.com",
mobile: "019894793"
}
包含 101 个文档:
{
_id: {
firstName: "foo",
lastName: "bar,
},
value: {
count: 21
duplicate: [{
id: undefined,
fullName: undefined,
DOB: undefined
},{
id: ObjectId("/*another object id*/"),
fullName: "foo bar",
DOB: ISODate("2000-01-02T00:00:00.000Z")
}]
},
}
包含 102 个文档:
{
_id: {
firstName: "foo",
lastName: "bar,
},
value: {
count: 22
duplicate: [{
id: undefined,
fullName: undefined,
DOB: undefined
},{
id: undefined,
fullName: undefined,
DOB: undefined
}]
},
}
我在 stackoverflow 上发现了另一个与我有类似问题的主题,但答案对我不起作用 MapReduce results seem limited to 100?
有什么想法吗?
编辑:
原始源代码:
var map = function () {
var value = {
count: 1,
userId: this._id
};
emit({lastName: this.lastName, firstName: this.firstName}, value);
};
var reduce = function (key, values) {
var reducedObj = {
count: 0,
userIds: []
};
values.forEach(function (value) {
reducedObj.count += value.count;
reducedObj.userIds.push(value.userId);
});
return reducedObj;
};
现在的源代码:
var map = function () {
var value = {
count: 1,
users: [this]
};
emit({lastName: this.lastName, firstName: this.firstName}, value);
};
var reduce = function (key, values) {
var reducedObj = {
count: 0,
users: []
};
values.forEach(function (value) {
reducedObj.count += value.count;
reducedObj.users = reducedObj.users.concat(values.users); // or using the forEach method
// value.users.forEach(function (user) {
// reducedObj.users.push(user);
// });
});
return reducedObj;
};
我不明白为什么它会失败,因为我还将一个值 (userId) 推送到 reducedObj.userIds。
我在map 函数中发出的value 是否存在一些问题?
【问题讨论】:
-
您的 map 和 reduce 函数产品对象的形状是否完全相同?见stackoverflow.com/questions/14138344/…。如果您仍然遇到问题,请编辑您的问题以包含您的 map 和 reduce 函数。
标签: javascript mongodb mapreduce mongodb-query aggregation-framework