Open In App

MongoDB Update Operators

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB, one of the more popular NoSQL databases, provides several methods and functions for processing data. Updating documents is an important feature of working with MongoDB. In this article, we will understand the Update Operators with MongoDB in detail.

It is expected that readers have a basic knowledge of MongoDB, such as document structure and collections. Readers should also be familiar with CRUD operations before reading about update operators. You can start with some basic articles like MongoDB: An Introduction and What is MongoDB, How Does It Work And Its Features to get a comprehensive understanding.

The following modifiers can be used in update operations, such as db.collection.updateMany() and db.collection.findAndModify().

Update Operators

1. Fields

MongoDB allows you to update the individual fields within a document.

Modifier

Description

$set

Set the value of a field. The field is created if it does not exist, and so can be used for dynamic updates or adding new fields to documents.

$unset

The entire field can be removed from the document without having to remove invalid data, allowing greater security.

$rename

If restructuring document schema requires a change in field name, it can be renamed while still maintaining existing value.

2. Arrays

The following modifiers are useful for manipulating array data.

Modifier

Description

$addToSet

Adds unique elements to an array if they are missing and doesn’t add duplicate values.

$pop

Trims an array, dropping either the first or last element.

$pull

Allows elements in an array that match a particular query to be removed selectively based on some conditions.

$push

Adds an element to the end of an array, versatile and supports adding more than one element at a time.

3. Modifiers

MongoDB offers modifiers that bring additional functionality to the update operation.

Modifier

Description

$inc

Adds to the current value of a field, particularly effective for numeric fields. Supports implementing counters or tracking numerical changes.

$currentDate

Setting the value of a field to current date and time, used for timestamping operations or making sure that each operation is able to reflect its last update.

$setOnInsert

During an insert operation, only particular fields are specified. These will be added upon a successful insert but have no effect during any update thereafter.

4. Bitwise

Sub-Operator

Description

$and

Perform a bitwise AND operation

$or

Perform a bitwise OR operation

$xor

Perform a bitwise XOR operation

$not

Perform a bitwise NOT operation

Example: Update Operators

Example 1: Using $currentDate

Imagine you have a collection of blog posts, and when editing. This timestamping operation can be assisted by the $currentDate operator.

// Before Update
db.blogPosts.findOne({ _id: postId })

// Update using $currentDate
db.blogPosts.update(
{ _id: postId },
{ $currentDate: { lastModified: true } }
)

// After Update
db.blogPosts.findOne({ _id: postId })

Output:

// Before Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a117"),
title: "MongoDB Update Operators",
content: "Introduction to MongoDB update operators...",
lastModified: ISODate("2023-01-01T12:00:00Z")
}
// After Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a117"),
title: "MongoDB Update Operators",
content: "Introduction to MongoDB update operators...",
lastModified: ISODate("2023-12-13T15:30:00Z")
}

Before Updates

// Retrieve a blog post with a specific ID
db.blogPosts.findOne({ _id: postId })

Before doing any editing, this line first gets a blog post from the MongoDB collection named blogPosts. It does this by looking for a document with the specific _id (a unique identifier), which each blog post has.

Update using $currentDate

// Update the "lastModified" field to the current date and time
db.blogPosts.update({ _id: postId }, { $currentDate: { lastModified: true } })

This line updates a particular post in the blogPosts collection. This update is focused on the document with a given _id (unique identifier). The update operation uses the $currentDate operator to set its value of lastModified field into current date and time. In fact, it’s like adding a time stamp to the blog post showing when it was last modified.

After Update

// Retrieve the updated blog post
db.blogPosts.findOne({ _id: postId })

Following the update, this line retrieves again to observe how things have changed. Now, the lastModified field should be set to today’s date and time so that people can see when this blog post was last altered.

Example 2 : Using $inc and $set

Consider a scenario where you have a collection of products, and you want to update the inventory count and set a new discount for a specific product.

// Before Update
db.products.findOne({ _id: productId })

// Update using $inc and $set
db.products.update(
{ _id: productId },
{
$inc: { inventory: -5 }, // Decrement inventory by 5 units
$set: { discount: 0.1 } // Set a new discount of 10%
}
)

// After Update
db.products.findOne({ _id: productId })

Output:

// Before Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a118"),
name: "Smartphone XYZ",
inventory: 100,
discount: 0.05
}
// After Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a118"),
name: "Smartphone XYZ",
inventory: 95,
discount: 0.1
}

Before Updates

// Retrieve product information with a specific ID
db.products.findOne({ _id: productId })

This line retrieves a product document from the MongoDB collection products. It seeks a document with exactly the same_id as productId.

Update using $inc and $set

// Update the product with specified changes
db.products.update(
{ _id: productId },
{
$inc: { inventory: -5 }, // Decrease inventory by 5 units
$set: { discount: 0.1 } // Set a new discount of 10%
}
)

This block updates a particular product in the products collection. The product is identified by its unique_id. The update operation uses two operators:

  • $inc: This operator increments (or in this case, decrements with a negative value) the current value of a field. In this example, it decreases the inventory field by 5 units.
  • $set: This operator sets the value of a field. Here, it sets the discount field to 0.1, representing a new discount of 10%.

After Updates

// Retrieve the updated product information
db.products.findOne({ _id: productId })

Following the update, this line retrieves the same product to see the changes. Now, the inventory should be reduced by 5 units, and the discount should reflect the new value of 0.1.

This code is effectively updating a product’s information in MongoDB. It decreases the inventory by 5 units and sets a new discount of 10%, providing a practical example of how to modify data in a MongoDB collection.

Conclusion

MongoDB Updatе Opеrators is еffеctivе data managеmеnt. Thе operators providеs a powerful toolkit for your data to meet evolving requirements. Whether it’s updating fields, arrays, or introducing new elements, MongoDB’s updatе capabilitiеs offеr flexibility and precision.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads