Lecture Notes Of Day 26:
MongoDB with Node.js
Objective:
Integrate MongoDB with Node.js to
build web applications.
Outcome:
By the end of the session,
students will be able to connect to MongoDB using the Node.js MongoDB driver
and perform CRUD (Create, Read, Update, Delete) operations.
1.
Introduction to MongoDB
- MongoDB is
a NoSQL database, meaning it does not store data in the traditional
relational format. Instead, it stores data in a flexible, JSON-like format
known as BSON (Binary JSON).
- It
is highly scalable and can handle large volumes of data without requiring
complex schema changes. MongoDB is ideal for building modern web
applications where the data structure may evolve over time.
Key
Features of MongoDB:
- Document-Oriented:
Stores data in BSON format, which is similar to JSON.
- Schema-less:
Data does not require a predefined structure.
- Scalability:
Easily handles large amounts of data and grows as needed.
- High
Availability: Supports replication and sharding for data
availability.
2.
Introduction to MongoDB and Node.js Integration
To interact with MongoDB in a
Node.js application, you need to install the MongoDB Node.js Driver.
This allows your application to connect, query, and modify data within MongoDB.
3.
Setting Up the Development Environment
Before proceeding, you should
have the following installed on your machine:
- Node.js
(with npm) installed on your computer.
- MongoDB
installed and running on your local machine or use a cloud-based service
like MongoDB Atlas.
Step-by-Step
Guide:
1. Install
MongoDB Node.js Driver:
First, you need to install the
MongoDB driver using npm in your Node.js project.
bash
CopyEdit
npm
install mongodb
2. Start
MongoDB Server:
If you are using a local
installation of MongoDB, start the MongoDB server. By default, it runs on mongodb://localhost:27017.
bash
CopyEdit
mongod
If you are using MongoDB Atlas,
create an account, set up a cluster, and obtain the connection string.
4.
Connecting to MongoDB
After setting up the environment,
the next step is to connect Node.js to MongoDB. Use the MongoDB Node.js driver
to establish a connection to the database.
Code
Example:
js
CopyEdit
const { MongoClient
} = require('mongodb');
//
MongoDB URI, update it based on your MongoDB server or Atlas credentials
const uri
= "mongodb://localhost:27017";
// Create
a new MongoClient
const
client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true
});
async function
main() {
try {
// Connect to the MongoDB cluster
await client.connect();
console.log("Connected to
MongoDB");
// Perform actions (e.g., CRUD operations)
here
} finally {
// Close the connection
await client.close();
}
}
main().catch(console.error);
- MongoClient:
This is the object used to interact with the database.
- connect():
Establishes a connection to MongoDB.
- client.close():
Closes the connection to the database once the operations are complete.
5.
Performing CRUD Operations
MongoDB allows for the standard CRUD
operations:
- Create:
Insert documents into a collection.
- Read:
Query and retrieve documents.
- Update:
Modify existing documents.
- Delete:
Remove documents.
5.1
Create Operation (Insert)
To insert documents into a
MongoDB collection, use the insertOne() or insertMany() methods.
Example
Code:
js
CopyEdit
async function
createDocument() {
const database = client.db("testDB");
// Accessing a database
const collection = database.collection("students");
// Accessing a collection
// Inserting a single document
const result = await collection.insertOne({ name:
"John Doe", age: 20, course: "Computer Science" });
console.log(`New student inserted with the following
id: ${result.insertedId}`);
}
createDocument().catch(console.error);
- insertOne():
Inserts one document into the collection.
- insertMany():
Inserts multiple documents at once.
5.2 Read
Operation (Find)
To retrieve documents from a
MongoDB collection, use the find() method.
Example
Code:
js
CopyEdit
async function
readDocuments() {
const database = client.db("testDB");
const collection = database.collection("students");
// Find one document
const student = await collection.findOne({ name:
"John Doe" });
console.log(student);
// Find multiple documents
const students = await collection.find({ age:
{ $gte: 18 } }).toArray();
console.log(students);
}
readDocuments().catch(console.error);
- findOne():
Finds a single document based on the query.
- find():
Finds multiple documents, returns a cursor. Use .toArray() to convert it
to an array.
5.3
Update Operation
To update documents in a MongoDB
collection, use updateOne(), updateMany(), or replaceOne().
Example
Code:
js
CopyEdit
async function
updateDocument() {
const database = client.db("testDB");
const collection = database.collection("students");
// Update a single document
const result = await collection.updateOne(
{ name: "John Doe" }, // Filter
{ $set: { age: 21 } } // Update operation
);
console.log(`${result.matchedCount}
document(s) matched the filter, ${result.modifiedCount} document(s) was/were
updated.`);
}
updateDocument().catch(console.error);
- updateOne():
Updates a single document that matches the filter.
- $set:
The operator used to modify the specified field in the document.
5.4
Delete Operation
To delete documents, use the deleteOne()
or deleteMany() methods.
Example
Code:
js
CopyEdit
async function
deleteDocument() {
const database = client.db("testDB");
const collection = database.collection("students");
// Delete one document
const result = await collection.deleteOne({ name:
"John Doe" });
console.log(`${result.deletedCount}
document(s) deleted.`);
}
deleteDocument().catch(console.error);
- deleteOne():
Deletes a single document based on the filter.
- deleteMany():
Deletes multiple documents based on the filter.
6.
Conclusion
By integrating MongoDB with
Node.js, you can build web applications that efficiently store and manage data.
The CRUD operations (Create, Read, Update, and Delete) enable you to interact
with the database to perform a wide range of data manipulation tasks.
Key
Takeaways:
- MongoDB
is a NoSQL database, ideal for handling unstructured data.
- The mongodb
Node.js driver allows you to connect and interact with MongoDB from
Node.js applications.
- CRUD
operations are fundamental for interacting with a database, and they are
performed using methods like insertOne(), find(), updateOne(), and deleteOne().
Homework/Practice:
- Implement
a simple application that performs CRUD operations on a collection of
books or students. Experiment with inserting multiple documents and
querying them using different filters.
