【问题标题】:nodejs - mongodb native find all documentsnodejs - mongodb native 查找所有文档
【发布时间】:2014-02-07 11:43:06
【问题描述】:

按照 nodejs 的 mongodb 手册中的示例,我从 db 中查找所有文档,如下所示

mongo.Db.connect(mongoUri, function (err, db) {
    if (err) {
        console.log(err);
    } 
    else {
        db.collection('test').find().toArray(function(e, d) {
            console.log(d.length);
            db.close();
        });
    }
});

现在我注意到整个集合被转换为一个数组。随着数据集的增长,这将不是理想的方法。无论如何要流式传输数据,这样它就不会每次都加载到内存中?

谢谢

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    最简单的方法是使用Cursor (reference):

    var cursor = db.collection('test').find();
    
    // Execute the each command, triggers for each document
    cursor.each(function(err, item) {
        // If the item is null then the cursor is exhausted/empty and closed
        if(item == null) {
            db.close(); // you may not want to close the DB if you have more code....
            return;
        }
        // otherwise, do something with the item
    });
    

    如果您需要进行大量计算,您可以考虑 Map-Reduce (reference) 是否适合您的需求,因为代码将在数据库服务器上执行,而不是在本地执行。

    【讨论】:

    • 感谢您对 map-reduce 的建议。我试图考虑这一点,但我不确定我是否理解 mongodb 上的 map-reduce 原理足以解决我的问题。但我一定会在未来重新审视。
    【解决方案2】:

    您可以通过在返回的光标上调用 stream() 来流式传输 node.js 原生驱动程序的查询结果:

    var stream = collection.find().stream();
    stream.on('data', function(doc) {
        console.log(doc);
    });
    stream.on('error', function(err) {
        console.log(err);
    });
    stream.on('end', function() {
        console.log('All done!');
    });
    

    【讨论】:

    • stream() 和 next() 有什么区别
    【解决方案3】:

    与循环方法相比,新的快速方法

    const data = await db.collection('parkingSigns').find().toArray();
    data // array with all the documents in the collection.
    

    【讨论】:

    • 这种方法在拥有 50 万条记录时会保持快速吗?
    • 它对于多达 50K 条记录的工作速度非常快,不确定是否为 500k,但应该比循环更快。
    【解决方案4】:

    是否可以选择限制查询?从字面上看是 db.collection.find().limit()?在将命令发送到服务器之前会解析限制,因此它只会扫描您的限制中的数据量。

    【讨论】:

    • 我的应用程序实际上需要对数据进行一些数学计算并返回最“相似”的文档。所以我要返回所有文档并在本地进行计算。现在,如果我可以在数据库本身上执行这些计算,那就太好了,但我不知道这是否可能?
    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 2016-11-09
    • 2017-01-12
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多