MongoDB aggregate $slice to get the length of the array

To get the length of an array in MongoDB using aggregation, use the $size operator within a $project stage. 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 collection with documents ?

db.demo382.insertOne({
    "Name": "David",
    "details": [
        {
            "SubjectName": "MySQL"
        },
        {
            "SubjectName": "MongoDB"
        },
        {
            "SubjectName": "Java"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e5b5e1c22064be7ab44e7f0")
}

Display all documents from the collection ?

db.demo382.find().pretty();
{
    "_id": ObjectId("5e5b5e1c22064be7ab44e7f0"),
    "Name": "David",
    "details": [
        {
            "SubjectName": "MySQL"
        },
        {
            "SubjectName": "MongoDB"
        },
        {
            "SubjectName": "Java"
        }
    ]
}

Example: Get Array Length Using $size

The following query uses aggregation to get the length of the details array ?

db.demo382.aggregate([
    { "$match": { "Name": "David" } },
    { "$project": { "count": { "$size": "$details" } } }
]);
{ "_id": ObjectId("5e5b5e1c22064be7ab44e7f0"), "count": 3 }

Key Points

  • The $size operator only works with array fields and returns the number of elements.
  • Use $match to filter documents before counting if needed.
  • The result includes the _id field by default unless explicitly excluded.

Conclusion

The $size operator in MongoDB aggregation pipeline efficiently counts array elements. Combine it with $project to return only the count value for each matching document.

Updated on: 2026-03-15T02:45:13+05:30

477 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements