Lesson 34 of 50 – CRUD Operations in Applications
68%

CRUD Operations in MongoDB Applications

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.

1. What Is CRUD?

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.

2. Set Up the Project

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.

3. Connect to MongoDB

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.

4. Create – Insert a Student

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.

5. Read – Find Students

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);

6. Update – Modify Student Details

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.

7. Delete – Remove a 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.

8. Complete CRUD Application

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.

9. CRUD Operations in a Real Application

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.

10. Practical Assignment

Complete the following tasks:

  1. Create a database named school.
  2. Create a collection named students.
  3. Insert three student documents with different details.
  4. Display all students using find().
  5. Find students whose city is "Patna".
  6. Update one student's course using updateOne().
  7. Delete a test student using its unique _id.
  8. Display the matched, modified, and deleted counts.
  9. Explain the four CRUD operations in your own words.
  10. Describe why a real application should validate input and check permissions.

🧠 Quick Quiz

1. Which method inserts one document into MongoDB?




2. Which operator changes selected fields in a document?




3. Which method removes one matching document?