Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Include all existing fields and add new fields to document in MongoDB?
To include all existing fields and add new fields to a document in MongoDB, use the $addFields operator in an aggregation pipeline. This operator preserves all existing fields while adding new computed fields to the output.
Syntax
db.collection.aggregate([
{
$addFields: {
"newField1": "value1",
"newField2": "$existingField",
"newField3": { $multiply: ["$field1", "$field2"] }
}
}
]);
Sample Data
db.addFieldDemo.insertOne({
"EmployeeId": 101,
"EmployeeName": "Larry",
"EmployeeDetails": {
"EmployeeSalary": 65000,
"EmployeeCity": "New York",
"Message": "Hi"
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5c7f654d8d10a061296a3c44")
}
Display Current Document
db.addFieldDemo.find().pretty();
{
"_id": ObjectId("5c7f654d8d10a061296a3c44"),
"EmployeeId": 101,
"EmployeeName": "Larry",
"EmployeeDetails": {
"EmployeeSalary": 65000,
"EmployeeCity": "New York",
"Message": "Hi"
}
}
Example: Add New Field from Nested Document
Extract the salary from the nested document and add it as a new top-level field ?
db.addFieldDemo.aggregate([
{
$addFields: {
"EmployeeBasicSalary": "$EmployeeDetails.EmployeeSalary"
}
}
]).pretty();
{
"_id": ObjectId("5c7f654d8d10a061296a3c44"),
"EmployeeId": 101,
"EmployeeName": "Larry",
"EmployeeDetails": {
"EmployeeSalary": 65000,
"EmployeeCity": "New York",
"Message": "Hi"
},
"EmployeeBasicSalary": 65000
}
Key Points
-
$addFieldspreserves all existing document fields unchanged. - Use dot notation to reference nested field values like
"$EmployeeDetails.EmployeeSalary". - New fields can contain static values, field references, or computed expressions.
Conclusion
The $addFields operator in aggregation pipelines allows you to add new computed fields while keeping all existing document structure intact. This is ideal for data transformation without losing original information.
Advertisements
