Assignments Of Day 26: MongoDB with Node.js
Assignment 1: Set Up MongoDB and Node.js Environment
Objective: Set up MongoDB and connect it to a Node.js project.
Instructions:
1. Install MongoDB on your local machine or use MongoDB Atlas.
2. Create a new Node.js project using npm init.
3. Install the MongoDB Node.js driver using the command npm install mongodb.
4. Write a script to connect to MongoDB and log a message on successful connection.
Step-by-Step Solution:
1. Install MongoDB (or use MongoDB Atlas).
2. Initialize a Node.js project:
bash
CopyEdit
npm init -y
3. Install MongoDB Node.js driver:
bash
CopyEdit
npm install mongodb
4. Write the following code in a file connect.js to establish a connection:
js
CopyEdit
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017"; // MongoDB URI for local connection
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function connectToMongo() {
try {
await client.connect();
console.log("Connected to MongoDB");
} finally {
await client.close();
}
}
connectToMongo().catch(console.error);
Assignment 2: Insert Data into MongoDB
Objective: Perform an insert operation to add data into a MongoDB collection.
Instructions:
1. Create a collection named students in MongoDB.
2. Insert a student document with name, age, and course fields.
Step-by-Step Solution:
1. Connect to MongoDB.
2. Create a students collection and insert a student document:
js
CopyEdit
async function insertData() {
const database = client.db("school");
const collection = database.collection("students");
const student = { name: "John Doe", age: 20, course: "Computer Science" };
const result = await collection.insertOne(student);
console.log(`New student inserted with ID: ${result.insertedId}`);
}
insertData().catch(console.error);
Assignment 3: Find One Document
Objective: Perform a read operation to fetch one document based on a query.
Instructions:
1. Use the findOne method to fetch a student by name from the students collection.
Step-by-Step Solution:
1. Connect to MongoDB.
2. Fetch a student by name:
js
CopyEdit
async function findOneStudent() {
const database = client.db("school");
const collection = database.collection("students");
const student = await collection.findOne({ name: "John Doe" });
console.log(student);
}
findOneStudent().catch(console.error);
Assignment 4: Find Multiple Documents
Objective: Fetch multiple documents based on a condition.
Instructions:
1. Insert several student documents with different ages.
2. Use the find() method to fetch students whose age is greater than or equal to 18.
Step-by-Step Solution:
1. Insert multiple students with varying ages.
2. Fetch students whose age is greater than or equal to 18:
js
CopyEdit
async function findMultipleStudents() {
const database = client.db("school");
const collection = database.collection("students");
const students = await collection.find({ age: { $gte: 18 } }).toArray();
console.log(students);
}
findMultipleStudents().catch(console.error);
Assignment 5: Update Data in MongoDB
Objective: Update a student's information.
Instructions:
1. Update the age of the student "John Doe" to 21.
Step-by-Step Solution:
1. Use updateOne() to update the document:
js
CopyEdit
async function updateStudent() {
const database = client.db("school");
const collection = database.collection("students");
const result = await collection.updateOne(
{ name: "John Doe" },
{ $set: { age: 21 } }
);
console.log(`${result.matchedCount} document(s) matched, ${result.modifiedCount} document(s) updated`);
}
updateStudent().catch(console.error);
Assignment 6: Delete Data from MongoDB
Objective: Delete a student's record from the students collection.
Instructions:
1. Delete the student document where the name is "John Doe".
Step-by-Step Solution:
1. Use deleteOne() to delete the student:
js
CopyEdit
async function deleteStudent() {
const database = client.db("school");
const collection = database.collection("students");
const result = await collection.deleteOne({ name: "John Doe" });
console.log(`${result.deletedCount} document(s) deleted`);
}
deleteStudent().catch(console.error);
Assignment 7: Insert Multiple Documents
Objective: Perform a bulk insert operation to add multiple students.
Instructions:
1. Insert multiple student documents into the students collection.
Step-by-Step Solution:
1. Use insertMany() to insert multiple documents:
js
CopyEdit
async function insertMultipleStudents() {
const database = client.db("school");
const collection = database.collection("students");
const students = [
{ name: "Alice", age: 22, course: "Mathematics" },
{ name: "Bob", age: 23, course: "Physics" }
];
const result = await collection.insertMany(students);
console.log(`${result.insertedCount} student(s) inserted`);
}
insertMultipleStudents().catch(console.error);
Assignment 8: Use Update to Modify Multiple Documents
Objective: Use updateMany() to update multiple documents.
Instructions:
1. Update the age of all students who are older than 21 to 25.
Step-by-Step Solution:
1. Use updateMany() to modify multiple documents:
js
CopyEdit
async function updateMultipleStudents() {
const database = client.db("school");
const collection = database.collection("students");
const result = await collection.updateMany(
{ age: { $gt: 21 } },
{ $set: { age: 25 } }
);
console.log(`${result.matchedCount} documents matched, ${result.modifiedCount} documents updated`);
}
updateMultipleStudents().catch(console.error);
Assignment 9: Query Data with Conditional Operators
Objective: Use MongoDB operators for more advanced queries.
Instructions:
1. Insert several students into the collection.
2. Query for students who are between the ages of 20 and 25.
Step-by-Step Solution:
1. Use MongoDB's conditional operators ($gte, $lte) for advanced queries:
js
CopyEdit
async function queryWithOperators() {
const database = client.db("school");
const collection = database.collection("students");
const students = await collection.find({ age: { $gte: 20, $lte: 25 } }).toArray();
console.log(students);
}
queryWithOperators().catch(console.error);
Assignment 10: Use Projection to Return Specific Fields
Objective: Retrieve specific fields from documents using projection.
Instructions:
1. Retrieve only the name and age fields of all students in the students collection.
Step-by-Step Solution:
1. Use projection to return specific fields:
js
CopyEdit
async function queryWithProjection() {
const database = client.db("school");
const collection = database.collection("students");
const students = await collection.find({}, { projection: { name: 1, age: 1 } }).toArray();
console.log(students);
}
queryWithProjection().catch(console.error);
