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

    Update Documents

    Updates in MongoDB are atomic per document and use update operators rather than rewriting whole documents.

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

    Introduction

    Updates in MongoDB are atomic per document and use update operators rather than rewriting whole documents. $set, $inc, $push, $unset — each does one job, surgically.

    Syntax reference

    js
    // Set + increment
    db.users.updateOne(
    { _id: 1 },
    { $set: { lastLogin: new Date() }, $inc: { loginCount: 1 } }
    );
    // Many
    db.products.updateMany({ stock: { $lt: 5 } }, { $set: { lowStock: true } });
    // Upsert
    db.counters.updateOne({ _id: "orders" }, { $inc: { seq: 1 } }, { upsert: true });

    Real-world use

    Every 'increment likes' or 'mark read' button in a UI maps to one update operator.

    Best practices

    • Use $inc for counters — atomic and safe under concurrency.
    • Use upsert: true for 'insert if missing'.
    Ready to mark this lesson complete?Track your journey across the entire course.