MongoDB query to create new field and count set the count of another field in it?

To create a new field and count elements from another field in MongoDB, use $addFields with $map and $size operators. This allows you to transform array elements and count their sizes in a single aggregation.

Syntax

db.collection.aggregate([
    {
        "$addFields": {
            "arrayField": {
                "$map": {
                    "input": "$arrayField",
                    "as": "element",
                    "in": {
                        "existingField": "$$element.existingField",
                        "newCountField": { "$size": "$$element.arrayToCount" }
                    }
                }
            }
        }
    }
]);

Sample Data

db.demo429.insertOne({
    "_id": 101,
    "Value": 3,
    "details": [
        {
            "Age": 29,
            "Value": 3,
            "details1": [1, 2, 3]
        },
        {
            "Age": 31,
            "Value": 4,
            "details1": [354]
        }
    ]
});

Example: Count Array Elements

Create a new field NumberOfDetails1 that counts elements in the details1 array ?

db.demo429.aggregate([
    {
        "$addFields": {
            "details": {
                "$map": {
                    "input": "$details",
                    "as": "d",
                    "in": {
                        "Age": "$$d.Age",
                        "NumberOfDetails1": { "$size": "$$d.details1" }
                    }
                }
            }
        }
    }
]);
{
    "_id": 101,
    "Value": 3,
    "details": [
        { "Age": 29, "NumberOfDetails1": 3 },
        { "Age": 31, "NumberOfDetails1": 1 }
    ]
}

How It Works

  • $addFields adds or modifies fields in documents
  • $map transforms each element in the array
  • $size counts the number of elements in an array
  • $$d refers to the current element being processed

Conclusion

Use $addFields with $map and $size to create new fields containing counts of array elements. This approach transforms nested arrays while preserving the document structure and adding computed count fields.

Updated on: 2026-03-15T02:57:22+05:30

709 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements