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

  • $addFields preserves 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.

Updated on: 2026-03-15T00:05:19+05:30

477 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements