Read All the Data From MongoDb Collection using Node.js


What do we intend to make ?

In this Chapter , we will Read all the data from the mongoDb collection "details".

Let's Start !

Step - 1 : Including Packages
We will start by requiring the package. We are using the following package in our application :

		        

var mongo = require('mongodb');
                
	            


Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.

		        

var new_db = "mongodb://localhost:27017/demo_db"



                
	            

  • demo_db is the name of the database. You can change it as per your wish.
  • 27017 is the port where our mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step - 3 : Read From DB
find() is an inbuilt method which is used to Read all data from the mongoDb collection.

		        
//read-all-occurance-mongodb-nodejs.js
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();
	});
});



                
	            

You can run the above code using the following command :

		        

D:\nj-learn-mongo>node read-all-occurance-mongodb-nodejs.js

				
	            

The output of the above code is :

		        

D:\nj-learn-mongo>node read-all-occurance-mongodb-nodejs.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 } ]