Count number of elements in an array with MongoDB?

To count the number of elements in an array in MongoDB, use the $size operator within the aggregation framework. The $size operator returns the number of elements in the specified array field.

Syntax

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

Sample Data

Let us create a sample collection with array data ?

db.countNumberOfElementsDemo.insertOne({
    "UserMessage": ["Hi", "Hello", "Bye", "Awesome"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cef8ec2ef71edecf6a1f6a1")
}

Display the document to verify the data ?

db.countNumberOfElementsDemo.find().pretty();
{
    "_id": ObjectId("5cef8ec2ef71edecf6a1f6a1"),
    "UserMessage": [
        "Hi",
        "Hello", 
        "Bye",
        "Awesome"
    ]
}

Count Array Elements

Use the $size operator to count elements in the UserMessage array ?

db.countNumberOfElementsDemo.aggregate([
    {
        $project: { 
            NumberOfElements: { $size: "$UserMessage" }
        }
    }
]);
{
    "_id": ObjectId("5cef8ec2ef71edecf6a1f6a1"),
    "NumberOfElements": 4
}

Key Points

  • The $size operator only works with arrays, not with other data types.
  • Use the $project stage in aggregation to include the count result.
  • The array field must be prefixed with $ to reference the field value.

Conclusion

The $size operator in MongoDB's aggregation framework provides an efficient way to count array elements. Combine it with $project to return the count alongside other document fields.

Updated on: 2026-03-15T01:37:16+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements