Mongodb-node.js Tutorial Series

Read the first occurrence of data in MongoDB collection using node.js

MongoDB-Nodejs tutorial | Perform mongodb operations using node.js



Overview

In this part of the mongodb operations using node.js tutorial series , we will learn about reading the first occurrence of data in mongodb collection using node.js .

Let's Start !!
Step 1 - Include Package

We will start by including mongodb npm package as shown below :

												
var mongo = require('mongodb');
												
											

Step-2 : Establish Connection

Establish a connection between the mongoDb database and our node.js app using the following :

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

  • demo_db is the name of the database. You can change it in accordance with your database name.
  • 27017 is the port where mongoDb is running.
  • Localhost i.e. 127.0.0.1 is the local IP.

Step-3 : Read the first occurrence of data

findOne() is an inbuilt method of mongodb which is used to read first occurrence of the data from a collection. An example is given below :

											
//read-one.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;
	}
	//findOne() reads the first occurance of any data from the database.
	db.collection("details").findOne({}, (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 :
											
>node read-one.js
Record Read successfully
{ name: 'Nodejsera',
  age: '23',
  mobile: '9876543210',
  _id: 59706a56a4f6761e3cc22c98 }								
										

What we learned

In this article we learned about

  1. Including monogdb npm package in your app.
  2. Establishing a connection between mongodb database and node.js application.
  3. find() method in mongodb used to read all the data from a collection