In this part of the mongodb operations using node.js tutorial series , we will learn about reading
all the data of a mongodb
collection using node.js
.
We will start by including mongodb
npm package as shown below :
var mongo = require('mongodb');
Establish a connection between the mongoDb database and our node.js app using the following :
var new_db = "mongodb://localhost:27017/demo_db"
find()
is an inbuilt method of mongodb
which is used to read all the data from a
collection. An example is given below :
//read-all.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//connecting to the database using nodejs
mongo.connect(new_db , function(error , db){
if (error){
throw error;
}
//Read All the data from the "details" collection.
db.collection("details").find({}).toArray( (err , collection) => {
if(err) throw err;
console.log("Record Read successfully");
console.log(collection);
db.close();
});
});
>node read-all.js
Record Read successfully
[ { name: 'Nodejsera',
age: '23',
mobile: '9876543210',
_id: 59706a56a4f6761e3cc22c98 },
{ name: 'rishabhio',
age: '25',
mobile: '1234567890',
_id: 59706c3771da112bd8b922dc },
{ name: 'rishabhio',
age: '25',
mobile: '1234567890',
_id: 597073b2c6f60f5b3c23a1a5 } ]
In this article we learned about
monogdb
npm package in your app. find()
method in mongodb used to read all the data from a collection