CRUD Operations in MongoDB using Node.js and Compass
Aim
To demonstrate the core CRUD operations — Create, Insert, Read, Update, and Delete — in MongoDB using the Compass GUI.
Procedure
- Open MongoDB Compass and connect to the local server at
mongodb://localhost:27017. - Create a new database called
college. - Inside it, create a collection named
students. - Insert a few student documents into the collection.
- Run Read, Update, and Delete operations on those documents.
- Check MongoDB Compass to confirm each operation went through correctly.
Algorithm
- Start MongoDB Compass and connect to the MongoDB server.
- Create the
collegedatabase. - Create the
studentscollection within it. - Insert student records into the collection.
- Display all student records.
- Update a student record.
- Delete a student record.
- Display the final set of records.
- Stop.
You'll need Node.js, MongoDB Community Server, MongoDB Compass (optional, for viewing data), and VS Code.
Check Node.js in the VS Code terminal:
node -v
npm -vCheck MongoDB by running:
mongoshIf mongosh opens successfully, MongoDB is running and available.
Open VS Code and create a folder named mongodb-lab. Open this folder in VS Code, then open a new terminal (Terminal → New Terminal) and run:
npm init -yThen install the MongoDB driver:
npm install mongodbCreate a file named app.js and use this code:
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://localhost:27017");
async function main() {
await client.connect();
const db = client.db("college");
const students = db.collection("students");
// Insert
await students.insertMany([
{ name: "Ravi", age: 20, branch: "CSE" },
{ name: "Sita", age: 21, branch: "CSE" }
]);
// Read
console.log("Students:");
console.log(await students.find().toArray());
// Update
await students.updateOne(
{ name: "Ravi" },
{ $set: { age: 21 } }
);
// Delete
await students.deleteOne({ name: "Sita" });
// Final records
console.log("Final Records:");
console.log(await students.find().toArray());
await client.close();
}
main();Make sure the MongoDB server is running, then in the VS Code terminal:
node app.jsExpected Output
[
{ _id: ..., name: 'Ravi', age: 20, branch: 'CSE' },
{ _id: ..., name: 'Sita', age: 21, branch: 'CSE' }
]
Final Records:
[
{ _id: ..., name: 'Ravi', age: 21, branch: 'CSE' }
]
The _id field is automatically generated by MongoDB.
Open MongoDB Compass and connect to mongodb://localhost:27017. You'll see the following structure:
└── students
└── Ravi
The final document looks like:
Result: The basic CRUD operations — Create, Read, Update, and Delete — were successfully demonstrated using MongoDB Compass.






good idea sir
ReplyDelete