Introduction
MongoDB with Node.js allows applications written in JavaScript to store, retrieve, update, and delete data in MongoDB. Node.js applications commonly connect to MongoDB using the official MongoDB Node.js driver. In this chapter, you will practice connecting Node.js to MongoDB, creating databases and collections, inserting documents, finding records, updating data, deleting documents, and closing the database connection. MongoDB with Node.js Practice questions with solutions to help you understand the concepts.
Q1. Install the MongoDB Node.js Driver
Problem Statement
Create a Node.js project and install the official MongoDB driver so that your application can communicate with MongoDB.
MongoDB Command / Query
Create a project:
mkdir mongodb-node-practice
cd mongodb-node-practice
npm init -y
Install the MongoDB driver:
npm install mongodb
Expected Output
The terminal should show a successful installation similar to:
added packages
Your project will contain:
mongodb-node-practice/
│
├── node_modules/
├── package.json
└── package-lock.json
Explanation
The mongodb npm package provides the official MongoDB Node.js driver.
Q2. Connect Node.js to MongoDB
Problem Statement
Write a Node.js program that connects to a MongoDB server running on the local computer.
MongoDB Command / Query
Create a file named app.js:
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
console.log("Connected to MongoDB");
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
main();
Run:
node app.js
Expected Output
Connected to MongoDB
Explanation
MongoClient is used to connect a Node.js application to MongoDB.
The connection string:
mongodb://127.0.0.1:27017
points to a MongoDB server running locally on the default MongoDB port.
Q3. Select a Database and Collection
Problem Statement
Connect to MongoDB and access a database named school and a collection named students.
MongoDB Command / Query
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
const db = client.db("school");
const students = db.collection("students");
console.log("Database and collection selected");
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
main();
Expected Output
Database and collection selected
Explanation
This code uses:
client.db("school")
to access the database and:
db.collection("students")
to access the collection.
The database and collection may be created when data is first written.
Q4. Insert One Document Using Node.js
Problem Statement
Insert one student document into the students collection using Node.js.
MongoDB Command / Query
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
const db = client.db("school");
const students = db.collection("students");
const result = await students.insertOne({
name: "Rahul",
age: 17,
course: "Python"
});
console.log("Inserted ID:", result.insertedId);
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
main();
Expected Output
Inserted ID: ObjectId("...")
Explanation
insertOne() inserts one document into the MongoDB collection.
MongoDB automatically generates an _id if you do not provide one.
Q5. Insert Multiple Documents Using Node.js
Problem Statement
Insert three students into the students collection using Node.js.
MongoDB Command / Query
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
const db = client.db("school");
const students = db.collection("students");
const result = await students.insertMany([
{
name: "Neha",
age: 16,
course: "Java"
},
{
name: "Aman",
age: 15,
course: "C++"
},
{
name: "Priya",
age: 17,
course: "JavaScript"
}
]);
console.log("Inserted:", result.insertedCount);
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
main();
Expected Output
Inserted: 3
Explanation
insertMany() inserts multiple documents in one operation.
The insertedCount property tells you how many documents were successfully inserted.
Q6. Find Documents Using Node.js
Problem Statement
Retrieve all students whose course is Python.
MongoDB Command / Query
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
const db = client.db("school");
const students = db.collection("students");
const result = await students
.find({ course: "Python" })
.toArray();
console.log(result);
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
main();
Expected Output
[
{
_id: ObjectId("..."),
name: "Rahul",
age: 17,
course: "Python"
}
]
Explanation
find() returns a cursor in the MongoDB Node.js driver.
Using:
.toArray()
converts the cursor results into a JavaScript array.
Q7. Find One Document Using Node.js
Problem Statement
Find the student whose name is Rahul.
MongoDB Command / Query
const result = await students.findOne({
name: "Rahul"
});
console.log(result);
Expected Output
{
_id: ObjectId("..."),
name: "Rahul",
age: 17,
course: "Python"
}
Explanation
findOne() returns one matching document or null if no matching document is found.
Unlike find(), you do not need to convert the result to an array.
Q8. Update a Document Using Node.js
Problem Statement
Update Rahul’s age from 17 to 18.
MongoDB Command / Query
const result = await students.updateOne(
{
name: "Rahul"
},
{
$set: {
age: 18
}
}
);
console.log("Matched:", result.matchedCount);
console.log("Modified:", result.modifiedCount);
Expected Output
Matched: 1
Modified: 1
Explanation
updateOne() updates the first document that matches the filter.
$set changes the value of the specified field without replacing the entire document.
Q9. Delete a Document Using Node.js
Problem Statement
Delete the student named Aman from the students collection.
MongoDB Command / Query
const result = await students.deleteOne({
name: "Aman"
});
console.log("Deleted:", result.deletedCount);
Expected Output
Deleted: 1
Explanation
deleteOne() removes the first document matching the specified filter.
If no document matches, deletedCount will be 0.
Q10. Perform CRUD Operations in One Node.js Program
Problem Statement
Create a simple Node.js program that performs the basic CRUD operations:
- Insert a student
- Read the student
- Update the student’s age
- Delete the student
MongoDB Command / Query
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
const db = client.db("school");
const students = db.collection("students");
// CREATE
const insertResult = await students.insertOne({
name: "Ravi",
age: 16,
course: "Node.js"
});
console.log("Inserted:", insertResult.insertedId);
// READ
const student = await students.findOne({
_id: insertResult.insertedId
});
console.log("Student:", student);
// UPDATE
const updateResult = await students.updateOne(
{
_id: insertResult.insertedId
},
{
$set: {
age: 17
}
}
);
console.log("Updated:", updateResult.modifiedCount);
// DELETE
const deleteResult = await students.deleteOne({
_id: insertResult.insertedId
});
console.log("Deleted:", deleteResult.deletedCount);
} catch (error) {
console.error(error);
} finally {
await client.close();
}
}
main();
Expected Output
Inserted: ObjectId("...")
Student: {
_id: ObjectId("..."),
name: "Ravi",
age: 16,
course: "Node.js"
}
Updated: 1
Deleted: 1
Explanation
This example demonstrates the complete basic CRUD flow between Node.js and MongoDB:
Node.js
↓
MongoDB Driver
↓
MongoDB
↓
Database → Collection → Documents
The four main operations are:
- Create →
insertOne() - Read →
find()/findOne() - Update →
updateOne() - Delete →
deleteOne()
Key Takeaways
- Node.js can communicate with MongoDB using the official
mongodbdriver. - Install the driver with
npm install mongodb. MongoClientis used to establish the MongoDB connection.client.db()accesses a database.db.collection()accesses a collection.insertOne()inserts one document.insertMany()inserts multiple documents.find()returns a cursor, which can be converted to an array usingtoArray().findOne()returns one matching document.updateOne()updates one matching document.deleteOne()deletes one matching document.async/awaitmakes asynchronous MongoDB operations easier to read.- Always close the MongoDB client when your application no longer needs the connection.
- Node.js + MongoDB is commonly used for building JavaScript backend applications.
FAQs
1. How does Node.js connect to MongoDB?
Node.js can connect to MongoDB using the official MongoDB Node.js driver and MongoClient.
2. Which npm package is used for MongoDB in Node.js?
The official package is called mongodb.
Install it with:
npm install mongodb
3. What is MongoClient in Node.js (MongoDB using Node.js)?
MongoClient is a class provided by the MongoDB Node.js driver that is used to connect an application to MongoDB.
4. How do you insert a document into MongoDB using Node.js?
Use insertOne():
await students.insertOne({
name: "Rahul",
age: 17
});
5. How do you retrieve MongoDB documents in Node.js?
Use find() for multiple documents:
const students = await collection.find({}).toArray();
For a single document, use:
const student = await collection.findOne({
name: "Rahul"
});
6. How do you update a MongoDB document using Node.js?
Use updateOne() with an update operator such as $set:
await collection.updateOne(
{ name: "Rahul" },
{ $set: { age: 18 } }
);
7. Can Node.js perform all MongoDB CRUD operations?
Yes. The MongoDB Node.js driver provides methods for creating, reading, updating, and deleting documents, including insertOne(), find(), updateOne(), and deleteOne().
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
