Get count of array elements from a specific field in MongoDB documents?

To count array elements from a specific field in MongoDB, use the $size operator within an aggregation pipeline. This operator returns the number of elements in an array field for each document.

Syntax

db.collection.aggregate([
    { $project: { count: { $size: "$arrayFieldName" } } }
]);

Sample Data

db.demo723.insertMany([
    {"Subject": ["MySQL", "MongoDB"]},
    {"Subject": ["C"]},
    {"Subject": ["C++", "Java", "Python"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5eab094d43417811278f588a"),
        ObjectId("5eab095243417811278f588b"),
        ObjectId("5eab095f43417811278f588c")
    ]
}

View Sample Data

db.demo723.find();
{ "_id": ObjectId("5eab094d43417811278f588a"), "Subject": ["MySQL", "MongoDB"] }
{ "_id": ObjectId("5eab095243417811278f588b"), "Subject": ["C"] }
{ "_id": ObjectId("5eab095f43417811278f588c"), "Subject": ["C++", "Java", "Python"] }

Example: Count Array Elements

Count the number of subjects for each document ?

db.demo723.aggregate([
    { $project: { count: { $size: "$Subject" } } }
]);
{ "_id": ObjectId("5eab094d43417811278f588a"), "count": 2 }
{ "_id": ObjectId("5eab095243417811278f588b"), "count": 1 }
{ "_id": ObjectId("5eab095f43417811278f588c"), "count": 3 }

Conclusion

The $size operator efficiently counts array elements within aggregation pipelines. It returns the exact number of elements in the specified array field for each document in the collection.

Updated on: 2026-03-15T03:51:03+05:30

830 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements