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
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.
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.
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.
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With