Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs - mongodb native find all documents

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?

Thanks

like image 896
dopplesoldner Avatar asked Feb 07 '14 11:02

dopplesoldner


People also ask

How do I get all my documents from MongoDB?

Using Java programCreate a MongoDB client by instantiating the MongoClient class. Connect to a database using the getDatabase() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method.

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.

How do I get data from MongoDB collection using node JS?

To select data from a collection in MongoDB, we can use the findOne() method. The findOne() method returns the first occurrence in the selection. The first parameter of the findOne() method is a query object.

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


1 Answers

new & fast way when compare to loop approach

const data = await db.collection('parkingSigns').find().toArray();
data // array with all the documents in the collection.
like image 154
TKdevlop Avatar answered Sep 20 '22 21:09

TKdevlop