MongoDB update operators offer powerful tools for modifying documents within a collection which provides flexibility and efficiency in database operations. From setting and unsetting fields to manipulating arrays and applying bitwise operations. In this article, we will understand different Update Operators which is used in MongoDB.
Update Operators
- Update operators in MongoDB are special commands used to modify documents within a collection. They provide powerful functionalities for updating specific fields, arrays, and embedded documents and ensuring efficient data manipulation without needing to retrieve and replace entire documents.
- MongoDB's update operators include
$set
for setting or updating field values, $unset
for removing fields, $inc
for incrementing numeric values, $addToSet
for adding unique elements to arrays, $push
for appending elements to arrays, $pull
for removing specific elements from arrays, $currentDate
for setting fields to the current date/time, and more.
1. Fields
MongoDB allows us 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.
Similar Reads
MongoDB - Field Update Operators
MongoDB offers a range of powerful field update operators that enable efficient modification of specific fields within documents. These operators allow developers to update specific fields in documents without rewriting the entire document, thus improving performance and operational efficiency. By g
5 min read
MongoDB Bitwise Update Operator
The MongoDB Bitwise Update Operator allows for efficient manipulation of integer fields within MongoDB documents through bitwise operations. In this article, We will learn about the MongoDB Bitwise Update Operator in detail by understanding various examples in detail. MongoDB Bitwise Update Operator
3 min read
MongoDB - $pop Operator
The $pop operator in MongoDB is designed for managing array fields by removing either the first or last element of the array. This operator simplifies the process of maintaining array size and managing data in scenarios where a fixed number of elements is required. In this article, We will learn abo
4 min read
MongoDB $subtract Operator
MongoDBâs $subtract operator is an essential tool in the aggregation pipeline, allowing users to perform subtraction operations on numbers, dates, and even date-time calculations. This powerful operator simplifies arithmetic operations within the aggregation pipeline and enhances MongoDB's ability t
4 min read
MongoDB $pow Operator
MongoDB's $pow operator is a powerful tool within the aggregation framework which is designed to compute exponentiation operations directly on numeric fields. In this article, We will learn about the MongoDB $pow Operator in detail by understanding various examples and so on. MongoDB $pow OperatorTh
4 min read
MongoDB $pull Operator
The $pull operator in MongoDB is a powerful update operator used to remove all instances of a specified value or values from an array. This operator is particularly useful for modifying arrays within documents without retrieving and updating the entire array manually. In this article, We will learn
5 min read
MongoDB $push Operator
The $push operator in MongoDB is a powerful tool used to update arrays within documents. It appends the entire array as a single element. To add each element of the array individually, the $each modifier can be used alongside $push. In this article, We will learn about the MongoDB $push Operator by
5 min read
MongoDB $sqrt Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages $sqrt operator is one of them. This operator is used to find the square root of a positive number and returns the result as a double. Syntax: { $sqrt: <number> } Here, the numbe
2 min read
MongoDB $size Operator
When working with data in MongoDB, arrays are a fundamental data type used to store multiple values in a single field. Whether we're handling lists of tags, categories, or other collections, it's often necessary to determine the size of an array. MongoDB provides the $size operator to help us effici
5 min read
MongoDB - $pullAll Operator
MongoDB $pullAll operator is a crucial tool for efficiently managing arrays within MongoDB documents. It allows users to remove all instances of specified values from an array and provides a direct way to update array fields. In this article, We will learn about the MongoDB $pullAll Operator by unde
3 min read