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

标签 javascript node.js mongodb

我使用的是 MongoDB v3.2,并且使用的是 native Nodejs 驱动程序 v2.1。在大型数据集(100 万以上文档)上运行聚合管道时,我遇到以下错误:

 'aggregation result exceeds maximum document size (16MB)'

这是我的聚合管道代码:

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 () {

            });

我尝试过的事情:

//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) {

})

我在其他答案( How could I write aggregation without exceeds maximum document size? )中看到我需要游标返回结果,那么我该如何正确地做到这一点?我似乎无法让它发挥作用。关于batchSize应该是多少有什么建议吗?

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

最佳答案

好吧,我明白了。它不起作用,因为我传递了一个回调函数作为聚合方法中的最后一个参数。通过传递 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);

关于javascript - 带有 NodeJS 驱动程序的 MongoDB 聚合游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36588164/

相关文章:

mongodb - mongorestore 错误失败 : EOF when restore DB from dump. gz

javascript - 从数字中获取字节问题

javascript - 使用 onBlur 隐藏表单,但这与提交按钮有冲突

javascript - HTML 对象没有以正确的……顺序显示?

javascript - 测试服务时没有调用 NestJS UseFilter

android - Loopback Android SDK 中的嵌套模型

node.js - 相当于 mongodb 中的 INET_ATON()

javascript - qt webengine 将 javascript 输出重定向到 GUI

node.js - 使用 html-pdf npm 包生成 pdf,作为 GET api 在 AWS 上部署

javascript - 将 iso-8859-1 转换为 utf-8 javascript