Create a collection called "Students" in MongoDB that contains fields such as Name, Roll No, Section, GPA. Demonstrate the CRUD operations by performing on it.
Mon Apr 07 2025 15:54:17 GMT+0000 (Coordinated Universal Time)
Saved by
@p9876543
const { MongoClient } = require('mongodb');
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'college';
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("✅ Connected to MongoDB");
const db = client.db(dbName);
const students = db.collection('Students');
// CREATE
await students.insertMany([
{ name: 'John', rollNo: 101, section: 'A', gpa: 3.7 },
{ name: 'Emma', rollNo: 102, section: 'B', gpa: 3.9 },
]);
console.log("📝 Students inserted.");
// READ
const allStudents = await students.find().toArray();
console.log("📄 All Students:", allStudents);
// UPDATE
await students.updateOne({ rollNo: 101 }, { $set: { gpa: 3.8 } });
console.log("🔧 GPA updated for Roll No 101.");
// DELETE
await students.deleteOne({ rollNo: 102 });
console.log("🗑️ Student with Roll No 102 deleted.");
} finally {
await client.close();
console.log("🔒 Connection closed.");
}
}
run().catch(console.error);
content_copyCOPY
Comments