Update with Aggregation Pipeline
Last Updated :
24 Feb, 2025
MongoDB is not just about storing and retrieving data. it also offers powerful tools for data manipulation and transformation. One such tool is the aggregation pipeline, which allows users to perform complex data processing operations within the database.
In this article, we'll explore how to use the aggregation pipeline for updating documents in MongoDB by covering concepts and examples in an easy-to-understand manner.
Aggregation Pipeline in MongoDB
The aggregation pipeline in MongoDB is a framework for performing data processing tasks within the database. It consists of stages representing a specific operation applied sequentially to the documents. Stages can include operations like grouping, sorting, filtering, and transforming documents.
The output of one stage serves as the input for the next stage in the pipeline. The aggregation pipeline allows for complex data processing and manipulation within MongoDB.
MongoDB introduced the ability to perform updates using aggregation pipeline expressions starting from version 4.2. This feature enables users to manipulate data in complex ways before updating documents.
Update with Aggregation Pipeline
- MongoDB update operations with aggregation pipeline expressions were introduced in version 4.2.
- This feature enables more complex update operations.
- Users can manipulate data in complex ways before updating documents.
- The aggregation pipeline expressions provide a powerful way to update documents by allowing for complex transformations.
- This capability enhances the flexibility and efficiency of update operations in MongoDB.
- Users can take the help from the aggregation framework's stages and operators to perform detailed data manipulations before updating documents.
Syntax:
The basic syntax for using aggregation pipeline in update operations is as follows:
db.collection.updateMany(
<filter>,
[
{
$set: {
<field>: <expression>
}
},
// Additional pipeline stages
]
)
Key Terms:
- <filter>: Specifies the selection criteria for documents to update.
- $set: Indicates the update operation to perform.
- <field>: Specifies the field to update.
- <expression>: Represents the aggregation expression to compute the new value for the field.
Example of Update with Aggregation Pipeline
To understand Update with Aggregation Pipeline we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called employees which contains information like name, salary, department and status of the employees in various documents.
[
{
"name": "John Doe",
"salary": 60000,
"department": "Engineering",
"status": "Senior"
},
{
"name": "Jane Smith",
"salary": 45000,
"department": "HR",
"status": "Junior"
},
{
"name": "Alice Johnson",
"salary": 75000,
"department": "Finance",
"status": "Senior"
},
...
]
Example 1: Updating Documents with Aggregation Pipeline
Let's consider a scenario where we have a collection named employees containing documents representing employee records. We want to update the salary field for all employees by adding a 10% bonus. We can achieve this using the aggregation pipeline in the update operation
Query:
db.employees.updateMany(
{},
[
{
$set: {
salary: { $multiply: ["$salary", 1.1] }
}
}
]
)
Output:
[
{
"name": "John Doe",
"salary": 66000,
"department": "Engineering",
"status": "Senior"
},
{
"name": "Jane Smith",
"salary": 49500,
"department": "HR",
"status": "Junior"
},
{
"name": "Alice Johnson",
"salary": 82500,
"department": "Finance",
"status": "Senior"
}
]
Explanation:
The filter {} selects all documents in the employees collection. The $set stage updates the salary field using the $multiply aggregation expression to calculate the new salary with a 10% bonus.
Using Aggregation Operators in Updates
MongoDB provides a wide range of aggregation operators that can be used within the aggregation pipeline for update operations. These operators enable users to perform various transformations and computations on the data before updating documents.
Example Using $cond Operator
Suppose we want to update the status field for all employees based on their salary. If the salary is greater than $50,000, set the status to "Senior"; otherwise, set it to "Junior". We can achieve this using the $cond operator within the update pipeline.
Query:
db.employees.updateMany(
{},
[
{
$set: {
status: {
$cond: {
if: { $gte: ["$salary", 50000] },
then: "Senior",
else: "Junior"
}
}
}
}
]
)
Output:
[
{
"name": "John Doe",
"salary": 60000,
"department": "Engineering",
"status": "Senior"
},
{
"name": "Jane Smith",
"salary": 45000,
"department": "HR",
"status": "Junior"
},
{
"name": "Alice Johnson",
"salary": 75000,
"department": "Finance",
"status": "Senior"
}
...
]
Explanation: The $cond operator evaluates the condition $gte (greater than or equal) to determine the value of the status field based on the salary.
Combining Multiple Stages
One of the key advantages of using the aggregation pipeline for updates is the ability to combine multiple stages to perform complex transformations in a single operation.
Example of Updating Multiple Fields
Suppose we want to update both the salary and department fields for all employees simultaneously. We can achieve this by adding multiple $set stages to the update pipeline
Query:
db.employees.updateMany(
{},
[
{
$set: {
salary: { $multiply: ["$salary", 1.1] }
}
},
{
$set: {
department: "Engineering"
}
}
]
)
Output:
[
{
"name": "John Doe",
"salary": 66000,
"department": "Engineering",
"status": "Senior"
},
{
"name": "Jane Smith",
"salary": 49500,
"department": "Engineering",
"status": "Junior"
},
{
"name": "Alice Johnson",
"salary": 82500,
"department": "Engineering",
"status": "Senior"
},
...
]
Explanation: Two $set stages are used to update the salary and department fields independently.
Conclusion
Overall, The ability to perform updates using the aggregation pipeline in MongoDB provides developers with a powerful tool for data manipulation and transformation. By understanding the aggregation expressions and operators, users can perform complex update operations with ease and eliminating the need for multiple queries to the database.
Similar Reads
Mongoose Aggregate.prototype.pipeline() API The Aggregate API.prototype.pipeline() method of the Mongoose API is used to perform aggregation tasks. It allows us to get the current pipeline operation object in the form of an array. It is useful to get all the current pipelining operations or pipeline methods we have applied to perform aggregat
2 min read
Aggregation Pipeline Stages in MongoDB - Set 1 MongoDB aggregation pipeline is a powerful framework for data processing that allows documents to perform sequential transformations like filtering, grouping, and reshaping. In this article, We will learn about various Aggregation Pipeline Stages in MongoDB with the help of examples and so on.Aggreg
8 min read
Aggregation Pipeline Stages in MongoDB - Set 2 In MongoDB, the Aggregation Pipeline is a powerful framework for processing and transforming data through several stages. Each stage performs a specific operation on the data, allowing for complex queries and aggregations. By linking multiple stages in sequence, users can effectively process and ana
14 min read
Aggregation Pipeline Optimization MongoDB's aggregation pipeline is a powerful tool for data transformation, filtering and analysis enabling users to process documents efficiently in a multi-stage pipeline. However, when dealing with large datasets, it is crucial to optimize the MongoDB aggregation pipeline to ensure fast query exec
6 min read
Elasticsearch Aggregations Elasticsearch is not just a search engine; it's a powerful analytics tool that allows you to gain valuable insights from your data. One of the key features that make Elasticsearch so powerful is its ability to perform aggregations. In this article, we'll explore Elasticsearch aggregations in detail,
4 min read
SQL | UPDATE with JOIN In SQL, the UPDATE with JOIN statement is a powerful tool that allows updating one table using data from another table based on a specific JOIN condition. This technique is particularly useful when we need to synchronize data, merge records, or update specific columns in one table by referencing rel
4 min read
MongoDB Aggregation Pipeline $limit The MongoDB aggregation pipeline is a powerful tool for data processing and transformation, allowing users to perform efficient filtering, sorting, grouping, and reshaping of documents. Among its various stages, the $limit stage is essential for restricting the number of documents that flow through
7 min read
Metric Aggregation in Elasticsearch Elasticsearch is a powerful tool not just for search but also for performing complex data analytics. Metric aggregations are a crucial aspect of this capability, allowing users to compute metrics like averages, sums, and more on numeric fields within their data. This guide will delve into metric agg
6 min read
Aggregation in MongoDB Aggregation in MongoDB is a powerful framework that allows developers to perform complex data transformations, computations and analysis on collections of documents. By utilizing the aggregation pipeline, users can efficiently group, filter, sort, reshape, and perform calculations on data to generat
7 min read
Aggregation in Data Mining Aggregation in data mining is the process of finding, collecting, and presenting the data in a summarized format to perform statistical analysis of business schemes or analysis of human patterns. When numerous data is collected from various datasets, it's important to gather accurate data to provide
7 min read