nodejs-mongodb native查找所有文档 [英] nodejs - mongodb native find all documents

查看:61
本文介绍了nodejs-mongodb native查找所有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是mongodb手册中关于nodejs的示例,我从数据库中找到了所有文档,如下所示:

Following an example from the mongodb manual for nodejs, I am finding all documents from a db as follows

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();
        });
    }
});

现在我注意到的是整个集合都被转换成一个数组.随着数据集的增长,这将不是理想的方法.无论如何,是否有 数据,这样就不会每次都将其加载到内存中?

Now what I notice is that the entire set is converted to an array. As the dataset will grow, this will not be the ideal approach. Is there anyway to stream the data so it is not loaded in memory every time?

谢谢

推荐答案

最简单的方法是使用Cursor(

The easiest way is to use a 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(

If there's a lot of computation you need to do, you might consider whether a Map-Reduce (reference) would fit your needs as the code would execute on the DB server, rather than locally.

这篇关于nodejs-mongodb native查找所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆