MongoDB: Updating Documents

Subject: nodejs

MongoDB: Updating Documents

Updating documents modifies existing records in a collection, keeping data current and accurate.

Why Update Documents?

  • Data Evolution: Change prices, addresses, statuses.
  • Correction: Fix errors or outdated info.
  • Enrichment: Add new fields.
  • Counters/Metrics: Increment/decrement numeric fields.
  • Array Management: Add/remove elements from arrays.

Core Concepts

  • Filter Document: Specifies which documents to update (like query filters).
  • Update Document: Contains update operators defining modifications.
  • Update Operators (must use):
    • $set: Set or add a field.
    • $inc: Increment/decrement numeric fields.
    • $unset: Remove a field.
    • $push: Add element(s) to array.
    • $pull: Remove element(s) from array.
    • $addToSet: Add element if not present.
    • $rename: Rename a field.
    • $currentDate: Set field to current date/time.

Methods

  • updateOne(filter, update, options): Update a single matched document.
  • updateMany(filter, update, options): Update multiple matched documents.
  • replaceOne(filter, replacement, options): Replace entire document (except _id).

Options include:

  • upsert: true: Insert if no match.
  • arrayFilters: Conditions to update specific array elements.

Node.js Examples

1. updateOne with $set and $inc

Update "Laptop Pro" price and decrement stock by 1.

2. updateMany with $set and $push

Change all "Peripherals" category and add "popular" tag to products with stock > 20.

3. replaceOne

Replace entire document for "External HDD".


Key Takeaways

  • updateOne() and updateMany() update specific fields using operators.
  • replaceOne() substitutes the entire document (except _id).
  • MongoDB updates are atomic per document.
  • upsert: true is useful for conditional insert-or-update.
  • Always use precise filters to avoid unintended changes.
Next : Joins and Data Relationships