Episode 8 of 17

Update Documents

Learn how to update documents in MongoDB using updateOne(), updateMany(), replaceOne(), and findOneAndUpdate(). Master update operators like $set, $unset, $inc, $push, $pull, $addToSet, and upsert operations.

Updating data is one of the most common operations in any database. MongoDB provides powerful update operators that go far beyond simple field replacement — you can increment counters, push items to arrays, rename fields, and even create documents if they don't exist (upsert).

updateOne() — Update the First Match

// Update a single document
db.users.updateOne(
    { email: "alice@example.com" },               // Filter
    { $set: { age: 29, lastUpdated: new Date() }} // Update
)

Output:

{
  acknowledged: true,
  matchedCount: 1,
  modifiedCount: 1
}

updateMany() — Update All Matches

// Give all developers a new field
db.users.updateMany(
    { role: "developer" },
    { $set: { department: "Engineering" } }
)

// Increment view count for all published posts
db.posts.updateMany(
    { published: true },
    { $inc: { views: 1 } }
)

Update Operators

$set — Set Field Values

// Set or update fields
db.users.updateOne(
    { name: "Alice" },
    {
        $set: {
            age: 29,
            "address.city": "Bangalore",   // Update nested field
            skills: ["JavaScript", "Go"]    // Set array
        }
    }
)

$unset — Remove Fields

// Remove a field from a document
db.users.updateOne(
    { name: "Alice" },
    { $unset: { temporaryField: "", oldEmail: "" } }
)

$inc — Increment/Decrement Numbers

// Increment likes by 1
db.posts.updateOne(
    { _id: postId },
    { $inc: { likes: 1 } }
)

// Decrement stock by 3
db.products.updateOne(
    { sku: "LAPTOP-001" },
    { $inc: { stock: -3 } }
)

// Increment multiple fields
db.analytics.updateOne(
    { page: "/home" },
    { $inc: { views: 1, uniqueVisitors: 1 } }
)

$min / $max — Conditional Updates

// Update only if new value is lower than current
db.products.updateOne(
    { sku: "LAPTOP-001" },
    { $min: { lowestPrice: 699 } }  // Only updates if 699 < current lowestPrice
)

// Update only if new value is higher than current
db.scores.updateOne(
    { player: "John" },
    { $max: { highScore: 1500 } }  // Only updates if 1500 > current highScore
)

$rename — Rename Fields

// Rename a field
db.users.updateMany(
    {},
    { $rename: { "fname": "firstName", "lname": "lastName" } }
)

Array Update Operators

$push — Add to Array

// Push a single item
db.posts.updateOne(
    { _id: postId },
    { $push: { comments: { user: "Bob", text: "Great post!" } } }
)

// Push multiple items
db.users.updateOne(
    { name: "Alice" },
    { $push: { skills: { $each: ["Python", "Docker", "AWS"] } } }
)

// Push and keep only the last 5 items
db.logs.updateOne(
    { server: "web-01" },
    {
        $push: {
            events: {
                $each: [{ type: "error", time: new Date() }],
                $slice: -5   // Keep only last 5
            }
        }
    }
)

$pull — Remove from Array

// Remove a specific value
db.users.updateOne(
    { name: "Alice" },
    { $pull: { skills: "Python" } }
)

// Remove items matching a condition
db.posts.updateOne(
    { _id: postId },
    { $pull: { comments: { user: "spammer" } } }
)

$addToSet — Add Unique Values

// Only adds if not already present
db.users.updateOne(
    { name: "Alice" },
    { $addToSet: { skills: "Go" } }  // Won't duplicate if "Go" exists
)

// Add multiple unique values
db.users.updateOne(
    { name: "Alice" },
    { $addToSet: { skills: { $each: ["Go", "Rust", "Python"] } } }
)

$pop — Remove First or Last Array Element

// Remove the last element
db.queue.updateOne(
    { name: "tasks" },
    { $pop: { items: 1 } }   // 1 = last, -1 = first
)

Upsert — Update or Insert

Upsert creates the document if it doesn't exist:

// If no document matches the filter, insert a new one
db.pageViews.updateOne(
    { page: "/about" },
    {
        $set: { lastVisited: new Date() },
        $inc: { count: 1 }
    },
    { upsert: true }  // Creates the document if it doesn't exist
)

findOneAndUpdate() — Update and Return

// Update and return the MODIFIED document
db.counters.findOneAndUpdate(
    { name: "orderId" },
    { $inc: { value: 1 } },
    { returnDocument: "after" }      // Return the updated document
)

// Update and return the ORIGINAL document (before update)
db.counters.findOneAndUpdate(
    { name: "orderId" },
    { $inc: { value: 1 } },
    { returnDocument: "before" }
)

replaceOne() — Replace Entire Document

// Replace the entire document (except _id)
db.users.replaceOne(
    { email: "old@example.com" },
    {
        name: "New User",
        email: "new@example.com",
        age: 30,
        role: "developer"
    }
)

Warning: replaceOne() replaces the entire document. Any fields not in the replacement document will be removed. Use $set if you only want to update specific fields.

What's Next

You can now update documents with precision — from incrementing counters to manipulating arrays. In the next episode, we'll learn how to remove documents using deleteOne(), deleteMany(), and findOneAndDelete().

TutorialMongoDBDatabaseNoSQL