Isaac.

MongoDB Basics

Get started with MongoDB: document-oriented NoSQL database.

By EMEPublished: February 20, 2025
mongodbnosqldatabasedocumentjson

A Simple Analogy

MongoDB is like a filing cabinet of folders. Each folder (document) contains information in whatever format makes sense—not forced into rigid columns. Files can have different structures, just like documents.


What Is MongoDB?

MongoDB is a document-oriented NoSQL database. Data is stored as flexible JSON documents instead of rigid tables, enabling flexible schemas and faster development.


Why Use MongoDB?

  • Flexibility: Documents can have different structures
  • Developer-friendly: JSON-like documents match code objects
  • Scalability: Horizontal scaling with sharding
  • Speed: No complex joins, data stored together
  • Rapid development: Schema changes are easy

Collections and Documents

// Collection: Users
// Document:
{
    _id: ObjectId("..."),
    name: "Alice",
    email: "alice@example.com",
    age: 30,
    tags: ["developer", "nodejs"],
    address: {
        street: "123 Main St",
        city: "NYC"
    }
}

Basic CRUD Operations

// INSERT
db.users.insertOne({
    name: "Bob",
    email: "bob@example.com",
    age: 25
});

// FIND
db.users.findOne({ email: "bob@example.com" });
db.users.find({ age: { $gt: 25 } });  // age > 25

// UPDATE
db.users.updateOne(
    { email: "bob@example.com" },
    { $set: { age: 26 } }
);

// DELETE
db.users.deleteOne({ email: "bob@example.com" });

Node.js Example

const { MongoClient } = require("mongodb");

async function main() {
    const client = new MongoClient("mongodb://localhost:27017");
    
    try {
        await client.connect();
        const db = client.db("myapp");
        const users = db.collection("users");
        
        // Insert
        await users.insertOne({ name: "Charlie", age: 28 });
        
        // Find
        const user = await users.findOne({ name: "Charlie" });
        console.log(user);
        
        // Update
        await users.updateOne(
            { name: "Charlie" },
            { $set: { age: 29 } }
        );
        
        // Delete
        await users.deleteOne({ name: "Charlie" });
    } finally {
        await client.close();
    }
}

main();

Query Operators

db.products.find({
    price: { $gte: 10, $lte: 100 },           // Range
    category: { $in: ["electronics", "books"] }, // Multiple values
    name: { $regex: "^L" },                     // Starts with L
    tags: { $all: ["new", "sale"] }             // All tags
});

Indexes and Performance

// Create index on email (faster queries)
db.users.createIndex({ email: 1 });

// Compound index
db.orders.createIndex({ userId: 1, createdDate: -1 });

// Check query performance
db.users.find({ email: "test@example.com" }).explain("executionStats");

Best Practices

  1. Embed related data: Store address with user if always accessed together
  2. Index frequently queried fields: email, userId, etc.
  3. Use meaningful _id: Auto-generated ObjectId is fine
  4. Validate on write: Ensure data quality
  5. Plan for growth: Consider sharding strategy early

Related Concepts to Explore

  • Aggregation pipelines
  • Transactions and atomicity
  • Replication and sharding
  • Schema validation
  • Mongoose ODM for Node.js

Summary

MongoDB provides flexible document storage ideal for rapid development. Master basic CRUD operations, queries, and indexing to build scalable applications with NoSQL databases.