Using MongoDB with NodeJS

Last updated on Jan 19 2023
Prabhas Ramanathan

Table of Contents

Node.js Create Connection with MongoDB

MongoDb is a NoSQL database. It can be used with Node.js as a database to insert and retrieve data.

Download MongoDB

Open the Linux Command Terminal and execute the following command:
1. apt-get install mongodb
It will download the latest MongoDB according to your system requirement.

n 24

Install MongoDB

After the complete download, use the following command to install MogoDB.
1. npm install mongodb –save
Use the following command to start MongoDb services:
1. service mongodb start

n 25

Now, connection is created for further operations.

Node.js MongoDB Create Database

To create a database in MongoDB, First create a MongoClient object and specify a connection URL with the correct ip address and the name of the database which you want to create.
Note: MongoDB will automatically create the database if it does not exist, and make a connection to it.

Example

Create a folder named “MongoDatabase” as a database. Suppose you create it on Desktop. Create a js file named “createdatabase.js” within that folder and having the following code:

1. var MongoClient = require('mongodb').MongoClient; 
2. var url = "mongodb://localhost:27017/MongoDatabase"; 
3. MongoClient.connect(url, function(err, db) { 
4. if (err) throw err; 
5. console.log("Database created!"); 
6. db.close(); 
7. });

Now open the command terminal and set the path where MongoDatabase exists. Now execute the following command:
1. Node createdatabase.js

n 26

Now database is created.

Node.js MongoDB Create Collection

MongoDB is a NoSQL database so data is stored in collection instead of table. createCollection method is used to create a collection in MongoDB.

Example

Create a collection named “employees”.

Create a js file named “employees.js”, having the following data:

1. var MongoClient = require('mongodb').MongoClient; 
2. var url = "mongodb://localhost:27017/ MongoDatabase"; 
3. MongoClient.connect(url, function(err, db) { 
4. if (err) throw err; 
5. db.createCollection("employees", function(err, res) { 
6. if (err) throw err; 
7. console.log("Collection is created!"); 
8. db.close(); 
9. }); 
10. });

Open the command terminal and run the following command:
1. Node employees.js

n 27

Now the collection is created.

Node.js MongoDB Insert Record

The insertOne method is used to insert record in MongoDB’s collection. The first argument of the insertOne method is an object which contains the name and value of each field in the record you want to insert.

Example

(Insert Single record)

Insert a record in “employees” collection.
Create a js file named “insert.js”, having the following code:

1. var MongoClient = require('mongodb').MongoClient; 
2. var url = "mongodb://localhost:27017/ MongoDatabase"; 
3. MongoClient.connect(url, function(err, db) { 
4. if (err) throw err; 
5. var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" }; 
6. db.collection("employees").insertOne(myobj, function(err, res) { 
7. if (err) throw err; 
8. console.log("1 record inserted"); 
9. db.close(); 
10. }); 
11. });

Open the command terminal and run the following command:
1. Node insert.js

n 28

Now a record is inserted in the collection.

Insert Multiple Records

You can insert multiple records in a collection by using insert() method. The insert() method uses array of objects which contain the data you want to insert.

Example

Insert multiple records in the collection named “employees”.

Create a js file name insertall.js, having the following code:

1. var MongoClient = require('mongodb').MongoClient; 
2. var url = "mongodb://localhost:27017/ MongoDatabase"; 
3. MongoClient.connect(url, function(err, db) { 
4. if (err) throw err; 
5. var myobj = [ 
6. { name: "Mahesh Sharma", age: "25", address: "Ghaziabad"}, 
7. { name: "Tom Moody", age: "31", address: "CA"}, 
8. { name: "Zahira Wasim", age: "19", address: "Islamabad"}, 
9. { name: "Juck Ross", age: "45", address: "London"} 
10. ]; 
11. db.collection("customers").insert(myobj, function(err, res) { 
12. if (err) throw err; 
13. console.log("Number of records inserted: " + res.insertedCount); 
14. db.close(); 
15. }); 
16. });

Open the command terminal and run the following command:
1. Node insertall.js

n 29

You can see here 4 records are inserted.

Node.js MongoDB Select Record

The findOne() method is used to select a single data from a collection in MongoDB. This method returns the first record of the collection.

Example

(Select Single Record)

Select the first record from the ?employees? collection.
Create a js file named “select.js”, having the following code:

1. var http = require('http'); 
2. var MongoClient = require('mongodb').MongoClient; 
3. var url = "mongodb://localhost:27017/MongoDatabase"; 
4. MongoClient.connect(url, function(err, db) { 
5. if (err) throw err; 
6. db.collection("employees").findOne({}, function(err, result) { 
7. if (err) throw err; 
8. console.log(result.name); 
9. db.close(); 
10. }); 
11. });

Open the command terminal and run the following command:
1. Node select.js

n 30

Select Multiple Records

The find() method is used to select all the records from collection in MongoDB.

Example

Select all the records from “employees” collection.
Create a js file named “selectall.js”, having the following code:

1. var MongoClient = require('mongodb').MongoClient; 
2. var url = "mongodb://localhost:27017/MongoDatabase"; 
3. MongoClient.connect(url, function(err, db) { 
4. if (err) throw err; 
5. db.collection("employees").find({}).toArray(function(err, result) { 
6. if (err) throw err; 
7. console.log(result); 
8. db.close(); 
9. }); 
10. });

Open the command terminal and run the following command:
1. Node selectall.js

n 31

You can see that all records are retrieved.

Node.js MongoDB Filter Query

The find() method is also used to filter the result on a specific parameter. You can filter the result by using a query object.

Example

Filter the records to retrieve the specific employee whose address is “Delhi”.
Create a js file named “query1.js”, having the following code:

1. var http = require('http'); 
2. var MongoClient = require('mongodb').MongoClient; 
3. var url = "mongodb://localhost:27017/MongoDatabase"; 
4. MongoClient.connect(url, function(err, db) { 
5. if (err) throw err; 
6. var query = { address: "Delhi" }; 
7. db.collection("employees").find(query).toArray(function(err, result) { 
8. if (err) throw err; 
9. console.log(result); 
10. db.close(); 
11. }); 
12. });

Open the command terminal and run the following command:
1. Node query1.js

n 32

Node.js MongoDB Filter With Regular Expression

You can also use regular expression to find exactly what you want to search. Regular expressions can be used only to query strings.

Example

Retrieve the record from the collection where address start with letter “L”.
Create a js file named “query2”, having the following code:

1. var http = require('http'); 
2. var MongoClient = require('mongodb').MongoClient; 
3. var url = "mongodb://localhost:27017/MongoDatabase"; 
4. MongoClient.connect(url, function(err, db) { 
5. if (err) throw err; 
6. var query = { address: /^L/ }; 
7. db.collection("employees").find(query).toArray(function(err, result) { 
8. if (err) throw err; 
9. console.log(result); 
10. db.close(); 
11. }); 
12. });

Open the command terminal and run the following command:
1. Node query2.js

n 33

Node.js MongoDB Sorting

In MongoDB, the sort() method is used for sorting the results in ascending or descending order. The sort() method uses a parameter to define the object sorting order.
1. Value used for sorting in ascending order:
2. { name: 1 }
3. Value used for sorting in descending order:
4. { name: -1 }

Sort in Ascending Order

Example

Sort the records in ascending order by the name.
Create a js file named “sortasc.js”, having the following code:

1. var http = require('http'); 
2. var MongoClient = require('mongodb').MongoClient; 
3. var url = "mongodb://localhost:27017/ MongoDatabase"; 
4. MongoClient.connect(url, function(err, db) { 
5. if (err) throw err; 
6. var mysort = { name: 1 }; 
7. db.collection("employees").find().sort(mysort).toArray(function(err, result) { 
8. if (err) throw err; 
9. console.log(result); 
10. db.close(); 
11. }); 
12. });

Open the command terminal and run the following command:
1. Node sortasc.js

n 34

Sort in Descending Order

Example

Sort the records in descending order according to name:
Create a js file named “sortdsc.js”, having the following code:

1. var http = require('http'); 
2. var MongoClient = require('mongodb').MongoClient; 
3. var url = "mongodb://localhost:27017/ MongoDatabase"; 
4. MongoClient.connect(url, function(err, db) { 
5. if (err) throw err; 
6. var mysort = { name: -1 }; 
7. db.collection("employees").find().sort(mysort).toArray(function(err, result) { 
8. if (err) throw err; 
9. console.log(result); 
10. db.close(); 
11. }); 
12. });

Open the command terminal and run the following command:
1. Node sortdsc.js

n 35

So, this brings us to the end of blog. This Tecklearn ‘Using MongoDB with NodeJS’ blog helps you with commonly asked questions if you are looking out for a job in NodeJS Programming. If you wish to learn NodeJS and build a career in NodeJS Programming domain, then check out our interactive, Node.js Training, that comes with 24*7 support to guide you throughout your learning period.

Node.js Training

About the Course

Tecklearn’s Node.js certification training course familiarizes you with the fundamental concepts of Node.js and provides hands-on experience in building applications efficiently using JavaScript. It helps you to learn how to develop scalable web applications using Express Framework and deploy them using Nginx. You will learn how to build applications backed by MongoDB and gain in-depth knowledge of REST APIs, implement testing, build applications using microservices architecture and write a real-time chat application using Socket IO. Accelerate your career as a Node.js developer by enrolling into this Node.js training.

Why Should you take Node.js Training?

• As per Indeed.com data, the average salary of Node.js developer is about $115000 USD per annum.
• IBM, LinkedIn, Microsoft, GoDaddy, Groupon, Netflix, PayPal, SAP have adopted Node.js – ITJungle.com
• There are numerous job opportunities for Node.js developers worldwide. The job market and popularity of Node.js is constantly growing over the past few years.

What you will Learn in this Course?

Introduction to Node.js

• What is Node.js?
• Why Node.js?
• Installing NodeJS
• Node in-built packages (buffer, fs, http, os, path, util, url)
• Node.js Modules
• Import your own Package
• Node Package Manager (NPM)
• Local and Global Packages

File System Module and Express.js

• File System Module
• Operations associated with File System Module
• JSON Data
• Http Server and Client
• Sending and receiving events with Event Emitters
• Express Framework
• Run a Web Server using Express Framework
• Routes
• Deploy application using PM2 and Nginx

Work with shrink-wrap to lock the node module versions

• What is shrink-wrap
• Working with npmvet
• Working with outdated command
• Install NPM Shrinkwrap

Learn asynchronous programming

• Asynchronous basics
• Call-back functions
• Working with Promises
• Advance promises
• Using Request module to make api calls
• Asynchronous Commands

Integration with MongoDB and Email Servers

• Introduction to NoSQL Databases and MongoDB
• Installation of MongoDB on Windows
• Installation of Database GUI Viewer
• Inserting Documents
• Querying, Updating and Deleting Documents
• Connect MongoDB and Node.js Application
• Exploring SendGrid
• Sending emails through Node.js application using SendGrid

REST APIs and GraphQL

• REST API
• REST API in Express
• Postman
• MongoDB Driver API
• Express Router
• Mongoose API
• GraphQL
• GraphQL Playground

Building Node.js Applications using ES6

• ES6 variables
• Functions with ES6
• Import and Export withES6
• Async/Await
• Introduction to Babel
• Rest API with ES6
• Browsing HTTP Requests with Fetch
• Processing Query String
• Creating API using ES6
• Building Dashboard API
• Creating dashboard UI with EJS
• ES6 Aside: Default Function Parameters
• Data Validation and Sanitization

User Authentication and Application Security

• Authentication
• Types of Authentication
• Session Vs Tokens
• JSON Web Tokens
• Bcrypt
• Node-local storage

Understand Buffers, Streams, and Events

• Using buffers for binary data
• Flowing vs. non-flowing streams
• Streaming I/O from files and other sources
• Processing streams asynchronously
• File System and Security

Build chat application using Socket.io

• Getting Started
• Adding Socket.io To Your App
• Exploring the Front-end
• Sending Live Data Back & Forth
• Creating the Front-end UI
• Showing Messages In App
• Working with Time
• Timestamps
• Show Message Time In Chat App
• Chat application Project

Microservices Application

• Why Microservices?
• What is Microservices?
• Why Docker?
• What is Docker?
• Terminologies in Docker
• Child Processes
• Types of child process

 

 

0 responses on "Using MongoDB with NodeJS"

Leave a Message

Your email address will not be published. Required fields are marked *