$set and $unset

Learn $set and $unset from beginner fundamentals through production decisions expected from an experienced MongoDB engineer.

Lesson content

$set and $unset MongoMart experience path: This topic is taught through the same MongoMart e-commerce system used throughout the course. Shared database // Core MongoMart collections customers: { _id, name, email, addresses[], createdAt } products: { _id, sku, name, categoryId, price, attributes, stock } carts: { _id, customerId, items[], expiresAt } orders: { _id, orderNo, customerId, items[], status, total, orderedAt } inventory: { _id, sku, available, reserved, warehouseId } payments: { _id, orderId, providerRef, status, amount } notifications: { _id, customerId, type, payload, sentAt } Beginner foundation Define $set and $unset, identify what problem it solves, and run the smallest working example before adding abstraction. Real-world scenario The operations dashboard calculates product revenue, customer value, fulfilment time, and daily trends directly from orders. Practical example db.orders.aggregate([ { $match: { status: "paid" } }, { $unwind: "$items" }, { $group: { _id: "$items.productId", revenue: { $sum: { $multiply: ["$items.quantity", "$items.unitPrice"] } } } }, { $sort: { revenue: -1 } }, { $limit: 10 } ]) Intermediate reasoning Predict the exact documents read or changed. Test missing fields, nulls, duplicates, empty arrays, and boundary values. Validate the result with a second query or assertion. Advanced production use Measure behavior with realistic cardinality and concurrency. Add indexes or distributed features only after identifying the actual access pattern and failure mode. 10-year experience perspective Push selective stages early, control memory, avoid unbounded fan-out, validate shard routing, and materialize expensive recurring results when justified. Review checklist Correctness and atomicity Schema evolution and backward compatibility Performance and capacity evidence Security and privacy Failure recovery, monitoring, and ownership Easy example Find one customer by email and return only the fields needed by the screen. db.customers.findOne( { email: "asha@example.com" }, { name: 1, email: 1, status: 1 } ) How to verify the easy example Run it with representative input. Confirm the expected output. Try one missing, invalid, or boundary value. Advanced example Aggregate completed orders by customer, rank revenue, and verify the access pattern with execution statistics. db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$customerId", revenue: { $sum: "$total" } } }, { $setWindowFields: { sortBy: { revenue: -1 }, output: { revenueRank: { $denseRank: {} } } } }, { $limit: 20 } ]).explain("executionStats") Advanced review Explain the tradeoffs and assumptions. Test failure, scale, security, and recovery behavior. Capture evidence from tests, execution plans, logs, or review output. Additional practical guidance $set and $unset production detail Push selective stages early, control memory, avoid unbounded fan-out, validate shard routing, and materialize expensive recurring results when justified. Required evidence A repeatable setup and test case The expected successful result One failure or edge case Relevant explain, profiler, log, or monitoring output A rollback or recovery approach