Back to Home
    MongoDBMongoDB v7Intermediate

    MongoDB

    MongoDB CRUD, aggregation pipeline, indexes, schema design patterns, and Atlas search.

    10 min read
    mongodbnosqldatabasedocument

    CRUD

    1 topic

    Insert, Find, Update, Delete

    javascript
    // Insert
    db.users.insertOne({ name: "Alice", age: 30, tags: ["admin"] });
    db.users.insertMany([{ name: "Bob" }, { name: "Carol" }]);
    
    // Find
    db.users.find({ age: { $gt: 25 } });
    db.users.find({ name: /^A/i });      // Regex
    db.users.findOne({ _id: ObjectId("...") });
    db.users.find({}).sort({ age: -1 }).limit(10).skip(20);
    
    // Projection (select fields)
    db.users.find({}, { name: 1, email: 1, _id: 0 });
    
    // Update
    db.users.updateOne(
      { _id: id },
      { $set: { age: 31 }, $push: { tags: "editor" } }
    );
    db.users.updateMany({ age: { $lt: 18 } }, { $set: { minor: true } });
    
    // Upsert
    db.users.updateOne({ email: "[email protected]" }, { $set: { name: "Alice" } }, { upsert: true });
    
    // Delete
    db.users.deleteOne({ _id: id });
    db.users.deleteMany({ status: "inactive" });

    ⚠️ updateMany without a filter updates ALL documents — double-check the query

    💡 $push adds to arrays, $pull removes from arrays

    Aggregation Pipeline

    1 topic

    Pipeline Stages

    javascript
    db.orders.aggregate([
      // Stage 1: Filter
      { $match: { status: "completed", createdAt: { $gte: ISODate("2024-01-01") } } },
    
      // Stage 2: Join with users
      { $lookup: {
        from: "users",
        localField: "userId",
        foreignField: "_id",
        as: "user"
      }},
      { $unwind: "$user" },
    
      // Stage 3: Group & aggregate
      { $group: {
        _id: "$user.country",
        totalRevenue: { $sum: "$amount" },
        orderCount: { $sum: 1 },
        avgOrder: { $avg: "$amount" }
      }},
    
      // Stage 4: Sort & limit
      { $sort: { totalRevenue: -1 } },
      { $limit: 10 },
    
      // Stage 5: Reshape output
      { $project: {
        country: "$_id",
        totalRevenue: 1,
        orderCount: 1,
        _id: 0
      }}
    ]);

    💡 $match early to reduce documents before expensive stages

    ⚡ $lookup is MongoDB's JOIN — use indexes on the localField/foreignField

    Related Articles

    Background reading and deeper explanations for this sheet.

    Memory in AI Agents: Vector DB vs Structured State (and When to Use Both)

    AI agents feel smart only when they can remember the right things at the right time. In this practical guide, you’ll learn the difference between vector database memory and structured state, when each approach shines, and how to combine them in real-world agent workflows. We’ll walk through concrete examples, implementation patterns, and pitfalls to avoid so you can build reliable, context-aware agents.

    keyword overlap

    Building Autonomous Agents Without Overengineering: A Practical Guide for Real-World Teams

    Autonomous agents can automate meaningful work, but many projects fail because teams overbuild too early. This practical guide shows you how to design, ship, and improve useful agents with simple patterns, clear guardrails, and real-world examples—without turning your stack into a science project.

    keyword overlap

    Event-Driven Agents with Kafka Streams: A Practical Guide for Building Real-Time AI Workflows

    Event-driven agents let you move from slow, request/response automation to responsive systems that react in milliseconds to real-world signals. In this hands-on guide, you’ll learn how to design, build, and operate agentic workflows using Apache Kafka and Kafka Streams, with practical patterns, code snippets, and production-ready advice.

    keyword overlap

    How to Build and Monetize an AI SaaS: A Practical Step-by-Step Guide for Founders

    Building an AI SaaS is more accessible than ever—but turning it into a profitable business requires more than calling an API. In this practical guide, you’ll learn how to validate your idea, ship an MVP, design pricing, and grow revenue with real-world examples, architecture patterns, and implementation tips.

    keyword overlap