Updating Documents in MongoDB


Updating Documents in MongoDB

Updating documents in MongoDB involves modifying existing documents in a collection. MongoDB provides several methods for updating documents, allowing you to change single or multiple documents, and specify how the updates should be applied.

Methods for Updating Documents

  1. updateOne(): Updates a single document that matches the query.
  2. updateMany(): Updates multiple documents that match the query.
  3. replaceOne(): Replaces a single document entirely with a new document.
  4. findOneAndUpdate(): Finds a single document and updates it, returning the document before or after the update.

1. updateOne()

The updateOne() method updates a single document that matches the query. If multiple documents match the query, only the first one found will be updated.

Syntax:

db.collection.updateOne( filter, update, options )
  • filter: The query to select the document(s) to update.
  • update: The update operation to apply.
  • options: Optional settings (e.g., upsert).

Example: Updating a Single Document

To update a single user's age to 30 based on their email:

db.users.updateOne( { email: "johndoe@example.com" }, { $set: { age: 30 } } )

In this example, only the first document with the email "johndoe@example.com" will have its age field updated to 30.

2. updateMany()

The updateMany() method updates all documents that match the query criteria.

Syntax:

db.collection.updateMany( filter, update, options )

Example: Updating Multiple Documents

To increase the price by 10% for all products with a category of "electronics":

db.products.updateMany( { category: "electronics" }, { $mul: { price: 1.10 } } )

In this example, all documents in the products collection with a category of "electronics" will have their price increased by 10%.

3. replaceOne()

The replaceOne() method replaces an entire document that matches the query with a new document. The new document will overwrite the existing one completely.

Syntax:

db.collection.replaceOne( filter, replacement, options )
  • filter: The query to select the document to replace.
  • replacement: The new document that will replace the existing document.
  • options: Optional settings.

Example: Replacing a Document

To replace a user's document with a new document:

db.users.replaceOne( { email: "johndoe@example.com" }, { name: "John Doe", age: 31, email: "johndoe@example.com", updated_at: new Date() } )

In this example, the entire document for the user with email "johndoe@example.com" will be replaced with the new document.

4. findOneAndUpdate()

The findOneAndUpdate() method finds a single document, updates it, and optionally returns the document before or after the update.

Syntax:

db.collection.findOneAndUpdate( filter, update, options )
  • filter: The query to select the document.
  • update: The update operation to apply.
  • options: Optional settings, including returnOriginal (default true, returns the document before the update).

Example: Find and Update a Document

To find a document with the specified email, update the age, and return the updated document:

db.users.findOneAndUpdate( { email: "johndoe@example.com" }, { $set: { age: 32 } }, { returnOriginal: false } )

In this example, the findOneAndUpdate() method updates the age of the user and returns the updated document.

Update Operators

MongoDB provides several update operators to specify how documents should be updated.

  • $set: Sets the value of a field.
    { $set: { field: value } }
  • $unset: Removes a field.
    { $unset: { field: "" } }
  • $inc: Increments the value of a field.
    { $inc: { field: value } }
  • $mul: Multiplies the value of a field.
    { $mul: { field: value } }
  • $push: Adds an item to an array field.
    { $push: { arrayField: value } }
  • $addToSet: Adds a unique item to an array field.
    { $addToSet: { arrayField: value } }
  • $pull: Removes an item from an array field.
    { $pull: { arrayField: value } }
  • $rename: Renames a field.
    { $rename: { oldField: "newField" } }

Example of Using Update Operators

To increment a user’s age by 1:

db.users.updateOne( { email: "johndoe@example.com" }, { $inc: { age: 1 } } )

To add a new tag to an array field tags:

db.posts.updateOne( { _id: ObjectId("507f191e810c19729de860ea") }, { $push: { tags: "newTag" } } )