MongoDB mapReduce 方法意外的结果

MongoDB mapReduce method unexpected results

我的 mongoDB 中有 100 个文档,假设每个文档都可能与不同条件下的其他文档重复,例如名字和姓氏、电子邮件和手机 phone。

我正在尝试 mapReduce 这 100 个文档以具有键值对,如分组。

一切正常,直到我在数据库中拥有第 101 条重复记录。

与第 101 条记录重复的其他文档的 mapReduce 结果输出已损坏。

例如:

我现在正在处理 firstName 和 lastName。

当数据库包含 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
        }]
    },

}

我在 Whosebug 上发现了另一个与我有类似问题的主题,但答案对我不起作用 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 是否存在一些问题?

解释问题


这是一个常见的 mapReduce 陷阱,但很明显,您在这里遇到的部分问题是您找到的问题没有清楚甚至正确解释这一点的答案。所以这里的答案是合理的。

文档中经常被遗漏或至少被误解的要点是 here in the documentation:

  • MongoDB can invoke the reduce function more than once for the same key. In this case, the previous output from the reduce function for that key will become one of the input values to the next reduce function invocation for that key.

稍后在页面下方添加:

  • the type of the return object must be identical to the type of the value emitted by the map function.

在你的问题的上下文中,这意味着在某个时刻有 "too many" 重复键值被传递给 reduce 阶段在一次通过中对此采取行动,因为它将能够对较少数量的文档执行此操作。通过设计,reduce 方法被多次调用,通常从已经减少的数据中获取 "output" 作为它的一部分 "input" 进行另一次传递。

这就是 mapReduce 设计用于处理非常大的数据集的方式,通过处理 "chunks" 中的所有内容,直到最终 "reduces" 每个键的单一分组结果。这就是为什么下一条语句很重要的原因是 emitreduce 输出的结构需要完全相同,以便 reduce 代码能够正确处理它。

解决问题


您可以通过修复 map 中发送数据的方式以及 return 和 reduce 函数中的处理方式来纠正此问题:

db.collection.mapReduce(
    function() {
        emit(
            { "firstName": this.firstName, "lastName": this.lastName },
            { "count": 1, "duplicate": [this] } // Note [this]
        )
    },
    function(key,values) {
        var reduced = { "count": 0, "duplicate": [] };
        values.forEach(function(value) {
            reduced.count += value.count;
            value.duplicate.forEach(function(duplicate) {
                reduced.duplicate.push(duplicate);
            });
        });

        return reduced;
    },
    { 
       "out": { "inline": 1 },
    }
)

重点在emit的内容和reduce函数的第一行都可以看到。本质上,它们呈现出相同的结构。在 emit 的情况下,生成的数组只有一个元素并不重要,但无论如何您都以这种方式发送它。并排:

    { "count": 1, "duplicate": [this] } // Note [this]
    // Same as
    var reduced = { "count": 0, "duplicate": [] };

这也意味着 reduce 函数的其余部分将始终假设 "duplicate" 内容实际上是一个数组,因为这是它作为原始输入的方式,也是它的方式将 returned:

        values.forEach(function(value) {
            reduced.count += value.count;
            value.duplicate.forEach(function(duplicate) {
                reduced.duplicate.push(duplicate);
            });
        });

        return reduced;

替代解决方案


答案的另一个原因是考虑到您期望的输出,这实际上更适合 aggregation framework。它将比 mapReduce 更快地执行此操作,并且编写代码更简单:

db.collection.aggregate([
    { "$group": {
       "_id": { "firstName": "$firstName", "lastName": "$lastName" },
       "duplicate": { "$push": "$$ROOT" },
       "count": { "$sum": 1 }
    }},
    { "$match": { "count": { "$gt": 1 } }}
])

就是这样。您可以通过在需要时向其中添加 $out 阶段来写入集合。但基本上无论是 mapReduce 还是聚合,您仍然通过将 "duplicate" 项添加到数组中来对文档大小施加相同的 16MB 限制。

另请注意,您可以简单地执行 mapReduce 无法在此处执行的操作,并且仅 "omit" 结果中实际上不是 "duplicate" 的任何项目。 mapReduce 方法如果不先将输出生成到集合然后 "filtering" 在单独的查询中生成结果,就无法执行此操作。

该核心文档本身引用了:

NOTE
For most aggregation operations, the Aggregation Pipeline provides better performance and more coherent interface. However, map-reduce operations provide some flexibility that is not presently available in the aggregation pipeline.

所以这真的是一个权衡问题,哪个更适合手头的问题。