MongoDB Tutorial 0/120 lessons ~6 min read Lesson 106

    MongoDB Exercises

    Each of the next 14 lessons gives you a focused, hands-on workout.

    Course progress0%
    Focus
    4 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Each of the next 14 lessons gives you a focused, hands-on workout. The exercises in this lesson are quick warm-ups across the whole course — pick three a day, copy the snippets into a free Atlas cluster (or the Compass playground), and try every variation.

    The goal is fluency, not memorization. After 30 of these you'll think in pipelines.

    Understanding the topic

    How to practise effectively:

    • Set up Atlas free tier + Compass once — every exercise then runs in < 1 minute.
    • Always explain() your queries — does the index get used? is there a SORT stage?
    • Solve, then optimise — write a working version, then make it index-only.
    • Re-implement the same exercise in two drivers (Node + Python or Java) to internalise.

    Informative example

    Warm-up set — try each in mongosh:

    js
    // 1. Insert 1k random users
    db.users.insertMany(Array.from({length:1000}, (_,i)=>({
    email:`u${i}@x.io`, country:["US","DE","FR","IN"][i%4],
    signupAt:new Date(Date.now()-i*86400000), plan:["free","pro","ent"][i%3]
    })));
    // 2. Top 5 countries by user count
    db.users.aggregate([
    { $group:{ _id:"$country", n:{ $sum:1 } } },
    { $sort:{ n:-1 } }, { $limit:5 }
    ]);
    // 3. Update — bump every "free" user to "pro" if signed up before 2024
    db.users.updateMany(
    { plan:"free", signupAt:{ $lt:ISODate("2024-01-01") } },
    { $set:{ plan:"pro", upgradedAt:new Date() } }
    );
    // 4. Index-only query — verify with explain()
    db.users.createIndex({ country:1, plan:1, signupAt:-1 });
    db.users.find({ country:"DE", plan:"pro" })
    .sort({ signupAt:-1 }).limit(20).explain("executionStats");

    Best practices

    • Run each exercise on Atlas free tier — the only cost is your time.
    • Always check explain() after a query change.
    • Pair-program one exercise per week with a friend — fastest way to spot anti-patterns.
    Ready to mark this lesson complete?Track your journey across the entire course.