MongoDB 无法插入文档,因为它超过了 180 层嵌套

MongoDB cannot insert document because it exceeds 180 levels of nesting

我是 MongoDB 的新手,非常感谢您的帮助。

我正在尝试 map/reduce,使用 MongoDB 的 java 驱动程序 3.4.2。

我有一个集合 collectionA,其中包含如下文档:

{
    "_id" : ObjectId("5a29a6757c5def07307a4b6f"),
    "someProperty1" : "454545",
    "someProperty2" : "1234",
    "myArray" : [ 
        "1", 
        "2", 
        "3", 
    ]
}

我想得到myArray的所有组合:[1,2] [1,3] [2,1] [2,3] [3,1] [3,2]

最长的 myArray 有 20 个元素。

我试过使用以下方法:

db.collectionA.mapReduce(
    function () {
        var elem= this;
        this.myArray.forEach(function (parent) {
            elem.myArray.forEach(function (child) {
                if (parent !== child)
                    emit(parent, child);
                });
        });
    },

    function (key, values) {
        return {
            result: Array.from(new Set(values))
        };
    },
    {
        query: {
            $where: "this.myArray.length > 1"
        },
        out: "collectionB"
    });

当我用少量数据测试它时,它工作正常。问题是现在我在源集合中有 2150 万个文档,它抛出了这个异常。

Exception in thread "pool-3-thread-5" com.mongodb.MongoCommandException: Command failed with error 15: 'cannot insert document because it exceeds 180 levels of nesting' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "cannot insert document because it exceeds 180 levels of nesting", "code" : 15, "codeName" : "Overflow" } at com.mongodb.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:115) at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:114) at

我做错了什么?解决这个问题的正确方法是什么?

提前致谢。

嗯,原来我对 reduce 函数的工作方式有误解。仅仅靠运气(或者说倒霉,真的),它在处理少量数据时运行良好。我将 map 函数更改为 emit(parent, {result:[child]}); 和减少功能:

function (key, values) {
    resultSet = new Set();
    values.forEach(function (partialResult) {
        partialResult.result.forEach(function (elem) {
            resultSet.add(elem);
        });
    });
    return {
        result: Array.from(resultSet)
    };
}

很有魅力。