带有 NodeJS 驱动程序的 MongoDB 聚合游标

mik*_*yaa 0 javascript mongodb node.js

我使用的是 MongoDB v3.2,我使用的是本机 nodejs 驱动程序 v2.1。在大型数据集(1mil+ 文档)上运行聚合管道时,我遇到以下错误:

 'aggregation result exceeds maximum document size (16MB)'
Run Code Online (Sandbox Code Playgroud)

这是我的聚合管道代码:

var eventCollection = myMongoConnection.db.collection('events');
var cursor = eventCollection.aggregate([
                {
                    $match: {
                        event_type_id: {$eq: 89012}
                    }
                },
                {
                    $group: {
                        _id: "$user_id",
                        score: {$sum: "$points"}
                    }
                },
                {
                    $sort: {
                        score: -1
                    }
                }
            ],
            {
                cursor: {
                    batchSize: 500
                },
                allowDiskUse: true,
                explain: false
            }, function () {

            });
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情:

//Using cursor event listeners. None of the on listeners seem to work. Always get error about 16mb.
cursor.on("data", function (data) {
   console.log("Some data: ", data);
});
cursor.on("end", function (data) {
   console.log("End of data: ", data);
});

//Using forEach. Which I thought would allow for >16mb because it's used in conjunction with the batchSize and cursor.
cursor.forEach(function (item) {

})
Run Code Online (Sandbox Code Playgroud)

我在其他答案中看到(如何不超过最大文档大小的情况下编写聚合?)我需要通过游标返回结果,那么我该如何正确地做到这一点?我似乎无法让它发挥作用。关于batchSize应该是什么的任何建议?

我正在使用本机 mongodb 包 - https://github.com/mongodb/node-mongodb-native用于 nodejs 项目而不是 mongo 命令行。

mik*_*yaa 5

好吧,我想通了。它不起作用,因为我将回调函数作为聚合方法中的最后一个参数传入。通过传递 null,它允许流按预期工作。变化如下:

var cursor = eventCollection.aggregate([
            {
                $match: {
                    event_type_id: {$eq: 89012}
                }
            },
            {
                $group: {
                    _id: "$user_id",
                    score: {$sum: "$points"}
                }
            },
            {
                $sort: {
                    score: -1
                }
            }
        ],
        {
            cursor: {
                batchSize: 500
            },
            allowDiskUse: true,
            explain: false
        }, null);
Run Code Online (Sandbox Code Playgroud)