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);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter