How to Update MongoDB Field Using Value of Another Field
Last Updated :
05 Jul, 2024
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:

1. Using the $set Operator
This method directly modifies the value of a field belong to a document in a MongoDB collection.
// Putting 'discounted_price' field up by using $set operator as 'price' and 'discount'
db.products.updateMany(
{},
{ $set: { "discounted_price": { $subtract: ["$price", "$discount"] } }
);
// retrieves the result
db.products.find();
Output:

Explanation: In the given query we update the discounted_price field in the products collection discounting from the price field with the $set operator, and then retrieves all products from from the products collection.
2. Using Aggregation Pipeline with $addFields
This method can add new fields to a document or make changes to existing fields by using the aggregation framework's $addField stage. It makes it simple to do multiple operations for complex operations.
// Update 'full_name' field by concatenating 'first_name' and 'last_name' within aggregation pipeline
db.products.aggregate([
{
$addFields: {
"full_name": {"$concat": ["$name", " ", "$brand"]}
}
},
{
$out: "products" // Insert up-to-date records to replace old documents
}
]);
// retrieves the result
db.products.find();
Output:

Explanation: The above query updates the full_name field in the products collection using an aggregation pipeline by concatenating the name and brand fields and overwrites the original collection with the updated documents after that retrieves all documents from the products collection.
3. Using Aggregation Pipeline with $set
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.
Conclusion
Overall, Updating fields in MongoDB using values from other fields is a common requirement in database management. MongoDB offers a variety of methods including the $set operator, aggregation pipelines to solve this efficiently. By understanding these methods and best practices developers can maintain data integrity and perform complex data manipulations easily.
Similar Reads
Default Value in MongoDB using Node.js
Setting default values in MongoDB using Node.js can streamline the database management process by ensuring that certain fields always have an initial value even if they are not provided by the user. This practice is particularly useful for maintaining data integrity, setting fallback values, and sim
2 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to Find Items Without a Certain Field in MongoDB
In MongoDB, querying for documents that don't have a certain field can be a common requirement, especially when dealing with schemaless data. While MongoDB provides various querying capabilities, finding documents without a specific field can sometimes be difficult. In this article, we'll explore di
4 min read
How To Update An "array of objects" With Firestore?
Firestore, a NoSQL database from Firebase, is widely used for building real-time, scalable web and mobile applications. One of the common tasks while working with Firestore is updating documents, particularly when working with complex data structures like arrays of objects.In this article, we will w
6 min read
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 gu
5 min read
How to update single and multiple documents in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to Update the _id of MongoDB Document?
In MongoDB, the _id field serves as a unique identifier for each document in a collection. While MongoDB automatically generates _id values for documents upon insertion, there are scenarios where we might need to update the _id of a document. In this article, We will learn about How to update the _i
3 min read
Python MongoDB - find_one_and_update Query
The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in its original form and to return the updated document return_document has to be implemented in the code. Syntax:Â coll.find_one_and_update(filter, update, option
2 min read
How to Perform a findOne Operation in MongoDB using Node.js?
The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read
How to Find MongoDB Records Where Array Field is not Empty?
In MongoDB, retrieving documents where specific array fields are not empty. This is useful in scenarios where the presence of data within an array is crucial for filtering results. MongoDB provides several operators, such as $exists and $ne to facilitate the querying of documents based on the conten
3 min read