Native Querying MongoDB inside array and get the count

To query inside array and check for existence to get the count, use $exists. This operator checks whether a specific field exists within array elements and returns documents that match the condition.

Syntax

db.collection.count({
    "arrayField.nestedField": { $exists: true }
});

Sample Data

db.demo296.insertMany([
    {
        "id": 101,
        "Name": "Chris",
        "details": [
            {
                "SubjectId": [101, 103],
                "SubjectName": ["MySQL", "MongoDB"]
            },
            {
                "SubjectId": [102, 104],
                "SubjectName": ["Java", "C"]
            }
        ]
    },
    {
        "id": 102,
        "Name": "David",
        "details": [
            {
                "SubjectId": [110, 113]
            },
            {
                "SubjectId": [112, 114]
            }
        ]
    },
    {
        "id": 103,
        "Name": "Bob",
        "details": [
            {
                "SubjectName": ["C++", "Python"]
            },
            {
                "SubjectName": ["Spring", "Hibernate"]
            }
        ]
    }
]);

Display Documents

db.demo296.find();
{
    "_id" : ObjectId("5e4d51715d93261e4bc9ea3b"), "id" : 101, "Name" : "Chris", "details" : [
        { "SubjectId" : [ 101, 103 ], "SubjectName" : [ "MySQL", "MongoDB" ] },
        { "SubjectId" : [ 102, 104 ], "SubjectName" : [ "Java", "C" ] }
    ]
}
{
    "_id" : ObjectId("5e4d519b5d93261e4bc9ea3c"), "id" : 102, "Name" : "David", "details" : [
        { "SubjectId" : [ 110, 113 ] }, { "SubjectId" : [ 112, 114 ] }
    ]
}
{
    "_id" : ObjectId("5e4d52315d93261e4bc9ea3d"), "id" : 103, "Name" : "Bob", "details" : [
        { "SubjectName" : [ "C++", "Python" ] }, { "SubjectName" : [ "Spring", "Hibernate" ] }
    ]
}

Query Array and Get Count

Count documents where SubjectName field exists within the details array ?

db.demo296.count({
    "details.SubjectName": { $exists: true }
});
2

How It Works

The query "details.SubjectName": { $exists: true } uses dot notation to check if the SubjectName field exists in any element of the details array. It returns 2 because Chris and Bob have documents with SubjectName fields, while David's document only contains SubjectId fields.

Conclusion

Use $exists with dot notation to query nested array fields and count matching documents. This approach efficiently filters documents based on field existence within array elements.

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

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements