0% found this document useful (0 votes)
9 views27 pages

4-3 - Mongo DB and Node Js

This document provides an overview of Node.js with MongoDB, detailing its features, advantages, and installation process. It explains the differences between MongoDB and traditional RDBMS, outlines basic MongoDB commands, and describes how to perform CRUD operations using the MongoDB Node.js Driver. Additionally, it includes step-by-step instructions for setting up MongoDB and executing commands in the Mongo Shell.

Uploaded by

vibhavbhartiya13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views27 pages

4-3 - Mongo DB and Node Js

This document provides an overview of Node.js with MongoDB, detailing its features, advantages, and installation process. It explains the differences between MongoDB and traditional RDBMS, outlines basic MongoDB commands, and describes how to perform CRUD operations using the MongoDB Node.js Driver. Additionally, it includes step-by-step instructions for setting up MongoDB and executing commands in the Mongo Shell.

Uploaded by

vibhavbhartiya13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT-4 : Node.

js with MongoDB

Introduction,
MongoDB Create Database,
Create Collection, Insert, delete,
update, join, Sort, Query.
MongoDB
• MongoDB is a document database storing data
in a JSON format called BSON.
• It is open-source, cross-platform, and designed
for application development and scaling.
• The name 'MongoDB' is derived from
'Humongous' meaning enormous.
-built to store a huge amount of data and also perform fast

• Released in 2009 by Eliot Horowitz.


Key Features of MongoDB

• NoSQL Database (Non-Relational)


• Stores data as collections of JSON-based
documents
• Schema-less: No rigid table structure
• Scalable and designed for large datasets
• Supports numbers, strings, booleans,
arrays, and nested documents
Example of a MongoDB Document
{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}
The '{ }' curly braces represent the JSON object.
MongoDB vs RDBMS Terminology
• It is opposite to SQL based databases where it does not normalize data
under schemas and tables where every table has a fixed structure.

It does not have tables, rows, and columns

MongoDB (NoSQL Database) RDBMS (SQL Server, Oracle, etc.)


Database Database
Collection Table
Document Row (Record)
Field Column

• MongoDB collections can store documents with different fields.


A record in MongoDB is a document, which is a data structure
composed of key value pairs similar to JSON objects.
The field values may include numbers, strings, booleans, arrays,
or even nested documents.
Advantages of MongoDB
1. Stores data as JSON-based documents without
enforcing a schema, making it ideal for hierarchical
data.
2. Easy to scale up or down as needed; supports data
splitting across multiple servers.
3. Rich features like indexing, aggregation, and file
storage.
4. Fast performance with large datasets.
5. Provides drivers for various technologies (C#, Java,
Python, Node.js, etc.).
6. Offers tools to manage MongoDB databases
effectively.
MongoDB can be installed locally or hosted in
the cloud.

Cloud vs. Local MongoDB

1. Local MongoDB Server: Runs on your computer (using


the mongod command).

2. MongoDB Atlas (Cloud): Hosts your database on the


cloud. To use it, you need internet access and a
connection string.
Server (mongod) and Client
Server (mongod): Need to start it; don’t directly work in it.
Client: This is where we actually work, performing
operations such as:

• Using Mongo Shell- A command-line interface to


manually run commands.
• Using Node.js to write automated operations, allows
interaction through code.
• Using MongoDB Compass (GUI) to visualize data and
run queries.
MongoDB Server
• It is a service that runs in the background and is
responsible for storing, managing, and retrieving data.
• On installing MongoDB, it includes an executable called
mongod (Mongo Daemon), which starts MongoDB server.
Server’s Role:
• Hosts the database.
• Processes queries.
• Handles CRUD (Create, Read, Update, Delete) operations.
- Whenever working with MongoDB (manually or through
Node.js), it’s needed to first start the MongoDB server:
Open Command Prompt or Terminal. Run: mongod
Server will start on the default port 27017 & ready to accept
connections.
Step-by-step guide to install MongoDB, start the server,
and work with the Mongo Shell on our system:
Step 1: Install MongoDB
i) Download MongoDB:
Visit the official MongoDB Community Server.
Select the appropriate version for your OS.
ii) Install MongoDB:
Run the downloaded installer.
Select "Complete Installation" during the setup.
Ensure the option to install MongoDB as a Windows
service is checked (on Windows).
Install all components, including MongoDB Tools.
iii) Verify Installation:
MongoDB will be installed in the default directory:
C:\Program Files\MongoDB\Server\<version>\bin
<version> will be the version we installed (e.g., 8.0).
Step 2: Add MongoDB to PATH (Optional but Recommended)
• Go to Control Panel > System > Advanced System Settings >
Environment Variables.
• In the System Variables, find the Path variable and click Edit.
• Add the MongoDB bin directory path, C:\Program Files\
MongoDB\Server\<version>\bin
• Save and restart your Command Prompt to apply the changes.
• Now you can access mongod and mongo commands from any
location in the terminal.

Step 3: Start the MongoDB Server


• Open a Command Prompt or Terminal.
• Run the following command to start the MongoDB server:
mongod
• This will start the MongoDB server on the default port 27017.
You should see output like:
Waiting for connections on port 27017
• Note: Keep this terminal open while working with MongoDB.
Step 4 : Verify Installation: Open Command Prompt
• Open another Command Prompt or Terminal.
• Run the following command: mongod –version

• This will show the MongoDB server version if installed correctly.


• To open mongo shell, write command: mongosh
MongoDB 8.0 uses mongosh, not mongo.
If mongosh.exe is missing: You may need to manually
download mongosh from the MongoDB Shell Download
Page.
- Add its bin directory to your PATH environment variable,
similar to:
C:\Program Files\MongoDB\mongosh-2.3.2-win32-x64\bin
Reopen command prompt and run: mongosh

Mongo Shell open and connect it to the running MongoDB server:

Now you are ready to work with the Mongo Shell to interact with the database.
Step 5: Basic Commands in Mongo Shell

An Overview of Common MongoDB


Shell Commands
1) show dbs : Lists all dbs available on MongoDB server.
Example:
> show dbs

2) use <database_name> Switches to the specified db. If the


db does not exist, it creates a new one.
Example: > use student
switched to db student
3) Create collection( same as table in RDBMS)

4) List Collections: Check the available collections


in the database: >show collections
5(a). Insert Data
db.<collection>.insertOne() method: to insert a
single document in a collection. Example:
student> db.personal.insertOne({SName:"Abhi", SAge:20,
mobile:6547864432})

5(b). insertMany()
db.<collection>.insertMany() inserts multiple
documents into a collection. It cannot insert a single document.
KIET> db.department.insertMany([
... { "_did": 101, "department_name": "Computer Science" },
... { "_did": 102, "department_name": "Mathematics" }
... { "_did": 103, "department_name": "ECE" }
6) Query Data
db.<collection_name>.find(): Retrieves all documents from
the specified collection. Example:> db.personal.find()

7) Update Data
• MongoDB provides the following methods to
update existing documents in a collection:
- db.collection.updateOne() - Modifies a single
document in a collection.
- db.collection.updateMany() - Modifies one or more
documents in a collection.
7(a) Example: updateOne()

student> db.personal.updateOne
({SName:’Abhi’}, {$set:{SAge:19}})
7(b) Example: updateMany()

student> db.personal.updateMany ({SAge:20},


{$set: {$Age:22}})

8) Delete Data:
To Delete Documents in a Collection
2 methods to delete one or more documents in a collection.

a) db.collection.deleteOne() - Deletes the first matching


document in a collection.
Example: Employee>db.users.deleteOne({ ESalary: 70000 })

b) db.collection.deleteMany() - Deletes all the matching


documents in a collection.
Example: Employee>db.users.deleteMany({ ESalary: 70000 })
9) Exit the Mongo Shell
Command: exit
• Description: Exits the Mongo Shell session.
Example:
> exit

Step10 : Stop the MongoDB Server


• Go to the terminal where mongod is running.
• Press Ctrl + C to stop the server.
A Node.js program to perform CRUD operations
(Create, Read, Update, Delete) with MongoDB.
This example uses the MongoDB Node.js Driver.
MongoDB vs. MongoDB Node.js Driver
1. MongoDB Server:
The actual database engine where your data is
stored and managed.

2. MongoDB Node.js Driver:


A JavaScript library that lets your Node.js app
interact with the MongoDB server.
- Work as a bridge b/w Application & MongoDB server

Installation: npm install mongodb


Major Differences

MongoDB Node.js
Feature MongoDB Server Driver
Connects
Purpose Operates the database applications to the
database
Client-side library for
Platform Server-side software Node.js

Requires MongoDB
Dependency Works independently Server to function
MongoDB Node.js Driver Installation

1. Confirm node.js installed: > node –version


2. Initialize Your Node.js Project(ie. Current folder if not already done:
If you haven't set up a Node.js project, run: > npm init –y
This creates a package.json file in your project.
3- To use MongoDB with a Node.js application, install the driver using
npm:
C:\practice\mongoo> npm install mongodb
Cont….

4- Verify Installation: Check your node_modules folder or look


for mongodb in package.json under dependencies.
For CRUD and other operations, refer
the Program file

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy