How to use Aggregation Pipeline with $set In MongoDB
This method updates fields in a document using the aggregation framework’s $set stage. It allows for more advanced updates and can handle conditional updates or updates based on other fields in the document.
// Updating 'Discounted price' field as 'Price' field minus 'Discounted price' field using aggregation pipeline
db.products.aggregate([
{
$set: {
"discounted_price": { $subtract: ["$price", "$discount"] }
}
},
{
$out: "products" // remove the previously existing documents and replace them with new documents
}
]);
// retrieves the result
db.products.find();
Output:
Explanation: In the above query we discounted_price
field in the products
collection by subtracting the discount
from the price
using an aggregation pipeline and overwrites the existing collection with the updated documents. then retrieves all documents from the products
collection.
How to Update MongoDB Field Using Value of Another Field
In the NoSQL database, MongoDB is the most robust and flexible option for managing big data. One common problem that occurs when working with MongoDB is to Update the MongoDB field using the value of another field and change data within our database.
In this article, we will learn about How to Update the MongoDB field using the value of another field by understanding various methods along with the practical implementation and so on.
How to Update the MongoDB Field Using the Value of Another Field?
When working with MongoDB, we need to change or update the data in our database. This process is known as data manipulation. MongoDB provides several ways to manipulate data, including updating, deleting, and transforming it. Below is the method that helps us to Update the MongoDB field using the value of another field as follows:
- Using the $set Operator
- Using Aggregation Pipeline with $addFields
- Using Aggregation Pipeline with $set
Let’s set up an environment
db.products.insertMany([
{
"_id": 1,
"name": "Laptop",
"brand": "Dell",
"price": 1200,
"discount": 100
},
{
"_id": 2,
"name": "Smartphone",
"brand": "Samsung",
"price": 800,
"discount": 50
},
{
"_id": 3,
"name": "Headphones",
"brand": "Sony",
"price": 150,
"discount": 10
},
{
"_id": 4,
"name": "Tablet",
"brand": "Apple",
"price": 900,
"discount": 75
}
]);
Output: