Skip to content
FullStackDostFullStackDostLearn · Build · Level Up
  • All Courses
  • Updates
  • My Account
  • Practice
  • All Courses
  • Updates
  • My Account
  • Practice
  • Home
  • Web development

MongoDB (NoSQL)

Curriculum

  • 10 Sections
  • 31 Lessons
  • 10 Weeks
Expand all sectionsCollapse all sections
  • Introduction to MongoDB
    MongoDB is a NoSQL database that is designed for handling large volumes of unstructured or semi-structured data. Unlike traditional relational databases (RDBMS) that use tables and rows to organize data, MongoDB stores data in a flexible document-oriented format using JSON-like documents (BSON - Binary JSON). This makes it highly scalable, flexible, and performant for applications that need to handle varying types of data with complex structures.
    5
    • 1.1
      What is MongoDB?
    • 1.2
      Why MongoDB?
    • 1.3
      When to use MongoDB?
    • 1.4
      Key Features of MongoDB
    • 1.5
      Installing MongoDB
  • MongoDB Basic Operations
    MongoDB provides a rich set of basic operations for interacting with the database, including creating, reading, updating, and deleting data (often abbreviated as CRUD operations). Below are the basic operations that you can perform with MongoDB.
    2
    • 2.1
      Database and Collection Basics: Your First Steps in MongoDB
    • 2.2
      MongoDB CRUD Operations: Create, Read, Update, Delete
  • Advanced Querying Techniques
    MongoDB offers a rich set of querying capabilities, and as you work with larger datasets and more complex application requirements, you’ll often need to use advanced querying techniques. These techniques help you optimize performance, execute sophisticated queries, and leverage MongoDB’s powerful indexing and aggregation features.
    4
    • 3.1
      Query Filters and Operators
    • 3.2
      Advanced MongoDB Querying: Unlocking Powerful Data Retrieval
    • 3.3
      Sorting and Limiting Results
    • 3.4
      Aggregation Framework: Transform and Analyze Data in MongoDB
  • Data Modeling and Schema Design
    Data modeling and schema design are critical when using MongoDB (or any NoSQL database) to ensure efficient data storage, fast queries, and scalability. Unlike relational databases, MongoDB is schema-less, which means you are not required to define a fixed schema upfront. However, making the right design decisions from the beginning is essential for maintaining performance and avoid complications as your data grows.
    4
    • 4.1
      MongoDB Data Modeling: Designing for Performance and Scale
    • 4.2
      Document Structure
    • 4.3
      Schema Design Patterns
    • 4.4
      MongoDB and Relationships
  • Indexing and Performance Optimization
    In MongoDB, indexing is a critical part of performance optimization. Without proper indexes, MongoDB has to scan every document in a collection to satisfy queries, which can be very inefficient for large datasets. Indexes are used to quickly locate data without scanning every document, making reads faster and more efficient.
    3
    • 5.1
      Creating Indexes in MongoDB: Supercharge Your Queries
    • 5.2
      Using Text Search
    • 5.3
      Performance Optimization
  • Integrating MongoDB with a Web Application (Node.js)
    Integrating MongoDB with a web application built using Node.js is a common and powerful combination for building scalable and efficient web apps. MongoDB’s flexibility with JSON-like data and Node.js's asynchronous event-driven architecture work well together. In this guide, I'll walk you through the steps for integrating MongoDB with a Node.js web application, covering the essentials of setting up the connection, performing CRUD operations, and using popular libraries.
    3
    • 6.1
      Setting Up MongoDB with Node.js
    • 6.2
      Mastering CRUD Operations with Mongoose in Node.js
    • 6.3
      Error Handling and Validation
  • Security in MongoDB
    Security is an essential aspect when working with MongoDB, especially when handling sensitive data in production environments. MongoDB provides a variety of security features to help protect your data against unauthorized access, injection attacks, and other vulnerabilities. Here’s a guide on securing MongoDB and your Node.js application when interacting with MongoDB.
    2
    • 7.1
      MongoDB Security: Authentication and Authorization Essentials
    • 7.2
      Data Encryption in MongoDB: Securing Your NoSQL Data
  • Working with MongoDB in Production
    3
    • 8.1
      MongoDB Backup and Restore
    • 8.2
      MongoDB Scaling and Sharding
    • 8.3
      MongoDB Replication
  • Deploying and Monitoring MongoDB
    Working with MongoDB in a production environment requires careful planning, attention to detail, and best practices to ensure optimal performance, security, reliability, and scalability.
    3
    • 9.1
      Deploying MongoDB to Production: A Comprehensive Guide
    • 9.2
      Monitoring and Management
    • 9.3
      Summary for MongoDB deployment on Production
  • Building a Web App with MongoDB (Final Project)
    Demo Project (OneStopShop)
    2
    • 10.1
      Building the Application
    • 10.2
      Final Project Features

MongoDB CRUD Operations: Create, Read, Update, Delete

Namaste, future FullStackDost! In the world of databases, managing data effectively is paramount. Whether you’re building a social media app, an e-commerce platform, or a data analytics tool, you’ll constantly be performing four fundamental operations: Create, Read, Update, and Delete – collectively known as CRUD. These are the heartbeats of any data-driven application.

In this lesson, we’ll dive deep into how MongoDB, our powerful NoSQL database, handles these CRUD operations. We’ll use the mongosh interactive shell to execute commands directly, giving you hands-on experience. So, let’s get started and make our data dance!

Graphics Suggestion: An EduPress-style clean infographic showing four distinct icons for Create (e.g., a plus sign or document with a star), Read (e.g., a magnifying glass), Update (e.g., a pencil or refresh arrows), and Delete (e.g., a trash can). Each icon could be linked to a MongoDB logo.

1. Create Operations: Adding New Documents to Your Collection

Creating data means adding new documents to a MongoDB collection. Think of a collection as a table in a relational database, but instead of rows, we have flexible JSON-like documents.

Before we begin, ensure your MongoDB server is running and you’re connected via mongosh. We’ll be working with a database named fstackdost_db and a collection named users. If they don’t exist, MongoDB will create them automatically when you first insert data!


// Switch to (or create) our database
use fstackdost_db;
// Output: switched to db fstackdost_db
    

insertOne(): Adding a Single Document

The insertOne() method is used to add a single document into a specified collection. It’s straightforward and perfect for individual entries.


// Example: Adding a new user, John Doe
db.users.insertOne({
    name: "John Doe",
    age: 30,
    email: "john.doe@example.com",
    interests: ["coding", "reading"],
    address: {
        street: "123 Main St",
        city: "Techville"
    }
});
/*
Expected Output:
{
  acknowledged: true,
  insertedId: ObjectId("...") // A unique ID generated by MongoDB
}
*/
    

Notice how MongoDB automatically assigns a unique _id to each document if you don’t provide one. This _id acts as the primary key.

insertMany(): Adding Multiple Documents

When you need to add several documents at once, insertMany() is your go-to method. It takes an array of document objects as its argument, making bulk inserts efficient.


// Example: Adding multiple users in one go
db.users.insertMany([
    {
        name: "Jane Smith",
        age: 25,
        email: "jane.smith@example.com",
        interests: ["hiking", "photography"]
    },
    {
        name: "Alice Johnson",
        age: 28,
        email: "alice.j@example.com",
        interests: ["gaming", "cooking"],
        status: "active"
    },
    {
        name: "Bob Williams",
        age: 35,
        email: "bob.w@example.com",
        interests: ["coding", "sports"]
    }
]);
/*
Expected Output:
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("..."),
    '1': ObjectId("..."),
    '2': ObjectId("...")
  }
}
*/
    

Graphics Suggestion: Two document icons, one with a single plus sign (for insertOne) and another with multiple plus signs (for insertMany), both pointing towards a database icon.

2. Read Operations: Retrieving Data from Your Database

Reading data means querying and fetching documents from your collections. MongoDB offers powerful and flexible ways to find exactly what you need.

find(): Querying Multiple Documents

The find() method is the primary way to query documents. When called without any arguments, it returns all documents in a collection. However, its real power comes from its ability to filter, sort, and project data.


// Example: Find all documents in the 'users' collection
db.users.find();
/*
Expected Output (formatted for readability):
[
  {
    _id: ObjectId("..."),
    name: 'John Doe',
    age: 30,
    email: 'john.doe@example.com',
    interests: [ 'coding', 'reading' ],
    address: { street: '123 Main St', city: 'Techville' }
  },
  {
    _id: ObjectId("..."),
    name: 'Jane Smith',
    age: 25,
    email: 'jane.smith@example.com',
    interests: [ 'hiking', 'photography' ]
  },
  // ... more documents
]
*/
    

To make the output more readable in mongosh, you can chain .pretty():


db.users.find().pretty();
    

Querying with Filters

To find specific documents, you pass a query document (a JavaScript object) to find(). This object specifies the conditions that documents must meet.


// Example: Find users who are 30 years old
db.users.find({ age: 30 });

// Example: Find users whose name is "Jane Smith" AND age is 25
db.users.find({ name: "Jane Smith", age: 25 });

// Example: Find users older than 28 using the $gt (greater than) operator
db.users.find({ age: { $gt: 28 } });

// Example: Find users whose interests include "coding"
db.users.find({ interests: "coding" });
    

MongoDB supports a rich set of query operators like $lt (less than), $gte (greater than or equal), $in (value in an array), $or, and more.

Projecting Specific Fields

Sometimes you don’t need all the fields from a document. Projection allows you to specify which fields to include or exclude in the result. You pass a second document to find(), where 1 includes the field and 0 excludes it.


// Example: Find all users, but only return their name and email
db.users.find({}, { name: 1, email: 1, _id: 0 }); // _id is included by default, so we explicitly exclude it
/*
Expected Output:
[
  { name: 'John Doe', email: 'john.doe@example.com' },
  { name: 'Jane Smith', email: 'jane.smith@example.com' },
  // ...
]
*/
    

Sorting and Limiting Results

You can chain additional methods to find() to further refine your results:

  • .sort({ field: 1/-1 }): Sorts the results. 1 for ascending, -1 for descending.
  • .limit(N): Restricts the number of documents returned to N.

// Example: Find users older than 25, sort by age ascending, and limit to 2 results
db.users.find({ age: { $gt: 25 } }).sort({ age: 1 }).limit(2);
    

findOne(): Retrieving a Single Document

If you expect only one document to match your query (e.g., finding a user by a unique email), findOne() is more efficient. It returns the first document that matches the query, or null if no document is found.


// Example: Find a user by their unique email
db.users.findOne({ email: "john.doe@example.com" });
    

countDocuments(): Counting Matches

To simply get the number of documents that match a certain query, use countDocuments(). This is more efficient than fetching all documents and then counting them.


// Example: Count users older than 25
db.users.countDocuments({ age: { $gt: 25 } });
// Expected Output: 3 (or whatever matches your data)

// Example: Count all documents in the collection
db.users.countDocuments({});
    

Graphics Suggestion: A magnifying glass icon hovering over a stack of documents, with a filter funnel icon next to it, and a small counter (e.g., “3 results”) appearing at the bottom. This represents filtering, finding, and counting.

3. Update Operations: Modifying Existing Data

Update operations allow you to change the data within existing documents. MongoDB provides methods to update a single document, multiple documents, or even replace an entire document.

updateOne(): Updating the First Match

This method updates a single document that matches the specified filter. It takes two main arguments: the query filter and an update document (which typically uses update operators).


// Example: Update John Doe's age to 31 and add a new interest
db.users.updateOne(
    { name: "John Doe" }, // Query filter: find John Doe
    {
        $set: { age: 31, status: "active" }, // Set new age and status
        $push: { interests: "photography" } // Add 'photography' to interests array
    }
);
/*
Expected Output:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1, // Number of documents that matched the query
  modifiedCount: 1 // Number of documents that were actually changed
}
*/
    

updateMany(): Updating All Matches

If your query matches multiple documents and you want to apply changes to all of them, updateMany() is the method to use.


// Example: Increment the age of all users older than 25 by 1
db.users.updateMany(
    { age: { $gt: 25 } }, // Query filter: find users older than 25
    { $inc: { age: 1 } } // Update operation: increment age by 1
);
/*
Expected Output:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3, // Assuming 3 users matched
  modifiedCount: 3
}
*/
    

replaceOne(): Replacing an Entire Document

Be careful with replaceOne()! It replaces the *entire* document that matches the query with a new document. The _id field remains, but all other fields are overwritten unless explicitly included in the replacement document.


// Example: Replace John Doe's document completely
db.users.replaceOne(
    { email: "john.doe@example.com" }, // Query filter
    {
        name: "Jonathan Doe", // New name
        age: 32,
        email: "jonathan.doe@example.com", // Updated email
        occupation: "Software Engineer" // New field, old fields like 'interests' and 'address' are removed
    }
);
/*
Expected Output:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1
}
*/
    

After this, John Doe’s document will only have _id, name, age, email, and occupation. His old `interests` and `address` fields are gone!

Common Update Operators

MongoDB provides a rich set of update operators to perform specific modifications:

  • $set: Sets the value of a field. If the field does not exist, $set adds the new field with the specified value.
  • $inc: Increments the value of a field by a specified amount. Works only with numeric values.
  • $push: Adds a value to an array field. If the field is not an array, it creates it.
  • $pull: Removes all instances of a specified value from an array.
  • $unset: Removes a specified field from a document.
  • $rename: Renames a field.

Graphics Suggestion: A document icon with a “gear” or “wrench” icon overlaid, representing modification. Smaller icons for $set (equals sign), $inc (plus sign), $push (arrow into a box), $pull (arrow out of a box), $unset (X mark) could appear around it.

4. Delete Operations: Removing Data from Your Collections

Deleting operations allow you to remove documents or even entire collections from your database. Use these operations with caution, as deleted data is often irrecoverable without backups!

deleteOne(): Deleting the First Match

This method deletes at most one document that matches the specified query filter. It’s useful for removing unique entries.


// Example: Delete the user whose email is 'jane.smith@example.com'
db.users.deleteOne({ email: "jane.smith@example.com" });
/*
Expected Output:
{ acknowledged: true, deletedCount: 1 }
*/
    

deleteMany(): Deleting All Matches

To remove multiple documents that satisfy a given filter, use deleteMany(). If you pass an empty query document {}, it will delete *all* documents in the collection.


// Example: Delete all users whose age is less than or equal to 25
db.users.deleteMany({ age: { $lte: 25 } });
/*
Expected Output:
{ acknowledged: true, deletedCount: 1 } // Or more, depending on your data
*/

// CAUTION: This will delete ALL documents in the 'users' collection!
// db.users.deleteMany({});
    

drop(): Removing an Entire Collection

The drop() method is the most drastic deletion operation. It completely removes a collection from the database, including all its documents and indexes. This is irreversible!


// Example: Drop the entire 'users' collection
db.users.drop();
/*
Expected Output:
true // Indicates successful deletion
*/
    

Graphics Suggestion: A large trash can icon. For deleteOne, a single document falling in. For deleteMany, multiple documents falling in. For drop(), the entire stack of documents (representing a collection) falling into the trash.

Practice Exercise: Your First MongoDB Data Management

Now it’s your turn! Open your mongosh terminal and perform the following operations. You can create a new database called fstackdost_practice for this.

  1. Create:
    • Insert a single document into a new collection named products. The document should have fields like name, price, category, and stock.
    • Insert at least three more products into the products collection using a single command. Ensure one product has a category of “Electronics” and another has “Books”.
  2. Read:
    • Find all products in the products collection.
    • Find all products with a price greater than 50.
    • Find products in the “Electronics” category and only display their name and price. Exclude the _id.
    • Count how many products have a stock less than 10.
  3. Update:
    • Update the price of one specific product (e.g., by its name) to a new value.
    • For all products in the “Books” category, decrease their stock by 5.
    • Add a new field called last_updated with the current date (new Date()) to all products with a stock greater than 20.
  4. Delete:
    • Delete a single product by its name.
    • Delete all products that have a stock of 0.
  5. Bonus Challenge:
    • Find all products, sort them by price in descending order, and limit the results to the top 2 most expensive products.

Summary: Mastering MongoDB’s Core Data Operations

Fantastic work! You’ve just mastered the four pillars of data management in MongoDB: Create, Read, Update, and Delete. These CRUD operations are not just commands; they are the fundamental interactions you’ll have with your database, forming the backbone of almost every application you’ll ever build.

Remember, practice is key! The more you experiment with these commands in mongosh, the more intuitive they will become. You now have the essential tools to manage data effectively in MongoDB, setting a strong foundation for your full-stack development journey. Keep building, keep learning!

Database and Collection Basics: Your First Steps in MongoDB
Prev
Query Filters and Operators
Next

Copyright © 2026 FullStackDost. All Rights Reserved.

  • Privacy Policy
  • Terms of Service
  • Contact Support

Powered by EduPress