updateOne/updateMany with $set, $inc, $push, $pull, $unset, and upsert.
Field updates
db.products.updateOne(
{ sku: 'A1' },
{ $set: { price: 8.99 }, $inc: { views: 1 } }
)Practice: Use practice database in mongosh.
Array updates
db.products.updateOne(
{ sku: 'A1' },
{ $push: { tags: 'featured' }, $pull: { tags: 'sale' } }
)
Upsert
db.counters.updateOne(
{ _id: 'orders' },
{ $inc: { seq: 1 } },
{ upsert: true }
)
Important interview questions and answers
- Q: replaceOne vs update?
A: replaceOne overwrites entire document except _id. - Q: upsert?
A: Creates doc if filter matches nothing—great for counters, risky without care.
Self-check
- Increment views by 1.
- When is upsert appropriate?
Pitfall: upsert:true on loose filters can create accidental documents.
Interview prep
- $inc?
- Increments numeric field atomically.
- upsert?
- Inserts if no match on filter.