Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

MDB
MongoDB
0/10 completed
Beginner
What is MongoDB?Inserting and finding documentsUpdating and deleting
Intermediate
Query operatorsSorting, paging and projectionIndexes and explain()
Advanced
The aggregation pipelineJoins, facets and window functionsSchema design and validation
Pro
Drivers, transactions and scaling
Tracks / MongoDB / Beginner

Updating and deleting

Updates in MongoDB are powerful: instead of replacing whole documents, you describe changes with update operators like $set and $inc. The server applies them atomically to each document.

updateOne and updateMany

Both take a filter (which documents) and an update (what to change):

MongoDB shell (simulated) · editable

The result tells you how many documents matched and how many were actually modified. updateMany changes every match:

MongoDB shell (simulated) · editable

⚠️ Forgetting the operator is a classic mistake. updateOne({…}, { price: 5 }) is rejected by mongosh because it would replace the whole document. Try it:

MongoDB shell (simulated) · editable

The update operators

Operator Does Example
$set Set fields (creates them if missing) { $set: { status: 'shipped' } }
$unset Remove fields { $unset: { onSale: '' } }
$inc Add to a number (use negative to subtract) { $inc: { stock: -1 } }
$mul Multiply a number { $mul: { price: 1.1 } }
$rename Rename a field { $rename: { qty: 'quantity' } }
$min / $max Update only if smaller / larger { $max: { highScore: 950 } }
$currentDate Set to the current date { $currentDate: { updatedAt: true } }
MongoDB shell (simulated) · editable

$inc is atomic: if two requests run $inc: { stock: -1 } at the same moment, both decrements count. Reading a value in your app, changing it and writing it back can lose updates.

Updating arrays

Operator Does
$push Append an element ($each for several)
$addToSet Append only if not already present
$pull Remove elements matching a value or condition
$pop Remove the first (-1) or last (1) element
MongoDB shell (simulated) · editable

Updating one element: the $ and $[] operators

MongoDB shell (simulated) · editable

Upserts

With { upsert: true }, if nothing matches, MongoDB inserts a new document built from the filter plus the update. $setOnInsert sets fields only when inserting:

MongoDB shell (simulated) · editable

The first call inserted (see upsertedCount: 1); the second matched and incremented.

Replacing a document

replaceOne swaps the whole document for a new one (keeping _id):

MongoDB shell (simulated) · editable

Every field not in the replacement is gone. Use $set unless you really mean to replace everything.

Find and modify in one step

findOneAndUpdate updates a document and returns it, atomically. That's perfect for "claim the next job" or "get the next invoice number":

MongoDB shell (simulated) · editable

Deleting

MongoDB shell (simulated) · editable

⚠️ deleteMany({}) deletes every document in the collection. Always run the same filter with find() first to see what you're about to delete.

Many apps never truly delete important data. Instead they soft delete: $set: { deletedAt: new Date() }, and filter those out in queries.

Practice

  1. Give every product in the Kitchen category a 15% discount with $mul.
  2. Add the tag 'loyal' to every customer who has the 'vip' tag, without creating duplicates.
  3. Upsert a document into settings for { userId: 7 } that sets theme: 'dark', and run it twice.
  4. Delete all orders with status 'cancelled', checking with find first.
MongoDB shell (simulated) · editable
✎ Check your understanding

1.What does { $inc: { stock: -2 } } do?

2.What is the difference between $push and $addToSet?

3.What does { upsert: true } do when no document matches the filter?

← Inserting and finding documents