CRUD stands for Create, Read, Update, and Delete. These are the four basic operations used to manage data in an application. In this lesson, we will use MongoDB with Node.js to build a simple student management example.
| Operation | Purpose | MongoDB Method |
|---|---|---|
| Create | Insert new data | insertOne() |
| Read | Retrieve existing data | find(), findOne() |
| Update | Modify existing data | updateOne() |
| Delete | Remove existing data | deleteOne() |
These operations allow an application to manage records such as students, employees, products, and customers.
First, install Node.js and make sure a MongoDB server is available locally or through MongoDB Atlas.
Create a project folder and initialize Node.js:
mkdir mongodb-crud-app
cd mongodb-crud-app
npm init -y
Install the official MongoDB driver:
npm install mongodb
Create a file named app.js in this folder.
We will use the database school and the
collection students.
Import MongoClient and connect to the
MongoDB server.
const { MongoClient } = require("mongodb");
const uri = process.env.MONGODB_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("Connected to MongoDB!");
} catch (error) {
console.error("Connection error:", error.message);
} finally {
await client.close();
}
}
main();
This code connects to MongoDB and selects the
students collection. The collection
can be created automatically by MongoDB when data
is first inserted if it does not already exist.
Use insertOne() to insert a student
document into the collection.
const result = await students.insertOne({
name: "Rahul Kumar",
age: 20,
course: "Computer Science",
city: "Aurangabad"
});
console.log("Inserted ID:", result.insertedId);
Example document stored in MongoDB:
{
"_id": ObjectId("..."),
"name": "Rahul Kumar",
"age": 20,
"course": "Computer Science",
"city": "Aurangabad"
}
MongoDB automatically generates an _id
value if you do not provide one.
Use find() to retrieve multiple student
documents.
const result = await students.find({}).toArray();
console.log(result);
To find students from a particular city, provide a filter document.
const result = await students.find({
city: "Aurangabad"
}).toArray();
console.log(result);
To retrieve only one matching student, use
findOne().
const student = await students.findOne({
name: "Rahul Kumar"
});
console.log(student);
Use updateOne() with a filter and the
$set operator to change selected fields.
const result = await students.updateOne(
{ name: "Rahul Kumar" },
{
$set: {
age: 21,
city: "Patna"
}
}
);
console.log("Matched:", result.matchedCount);
console.log("Modified:", result.modifiedCount);
The filter identifies the document. The
$set operator updates the specified
fields without replacing the entire document.
For real applications, prefer a unique identifier
such as _id when updating a specific
student.
Use deleteOne() to remove the first
document matching the filter.
const result = await students.deleteOne({
name: "Rahul Kumar"
});
if (result.deletedCount === 1) {
console.log("Student deleted successfully.");
} else {
console.log("No matching student found.");
}
Be careful when deleting records. Always use an appropriate filter. An empty filter may target an unintended document.
The following complete example demonstrates all four CRUD operations. It uses a unique name for the sample record so it does not accidentally update or delete another student's record.
const { MongoClient } = require("mongodb");
const uri = process.env.MONGODB_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: "CRUD Demo Student",
age: 20,
course: "JavaScript",
city: "Aurangabad"
});
const studentId = insertResult.insertedId;
console.log("Created:", studentId);
// READ
let student = await students.findOne({
_id: studentId
});
console.log("Student:", student);
// UPDATE
const updateResult = await students.updateOne(
{ _id: studentId },
{
$set: {
age: 21,
city: "Patna"
}
}
);
console.log("Modified:", updateResult.modifiedCount);
// READ AGAIN
student = await students.findOne({
_id: studentId
});
console.log("Updated student:", student);
// DELETE
const deleteResult = await students.deleteOne({
_id: studentId
});
console.log("Deleted:", deleteResult.deletedCount);
} catch (error) {
console.error("Application error:", error.message);
} finally {
await client.close();
}
}
main();
Run the application:
node app.js
This example creates a record, reads it, updates it, reads the updated version, and finally deletes that same record. Run it against a development database because the delete operation removes data.
In a web application, CRUD operations are commonly connected to routes or API endpoints.
| HTTP Method | Example Route | Operation |
|---|---|---|
| POST | /students |
Create a student |
| GET | /students |
List students |
| GET | /students/:id |
Get one student |
| PUT or PATCH | /students/:id |
Update a student |
| DELETE | /students/:id |
Delete a student |
These routes are examples of a typical REST API design. They require server-side code to validate input, check permissions, and call the MongoDB driver.
Never trust data sent by a browser without validation. Production applications should also implement authentication, authorization, error handling, and suitable database access controls.
Complete the following tasks:
school.students.find().updateOne()._id.1. Which method inserts one document into MongoDB?
2. Which operator changes selected fields in a document?
3. Which method removes one matching document?