How to get distinct list of sub-document field values in MongoDB?

To get distinct list of sub-document field values in MongoDB, use the distinct() method with dot notation to access nested fields within arrays or embedded documents.

Syntax

db.collection.distinct("outerField.innerField");

Sample Data

Let us create a collection with student documents containing nested arrays ?

db.getDistinctListOfSubDocumentFieldDemo.insertMany([
    {
        "StudentId": 101,
        "StudentPersonalDetails": [
            {
                "StudentName": "John",
                "StudentAge": 24
            },
            {
                "StudentName": "Carol",
                "StudentAge": 21
            }
        ]
    },
    {
        "StudentId": 102,
        "StudentPersonalDetails": [
            {
                "StudentName": "Carol",
                "StudentAge": 26
            },
            {
                "StudentName": "Bob",
                "StudentAge": 21
            }
        ]
    },
    {
        "StudentId": 103,
        "StudentPersonalDetails": [
            {
                "StudentName": "Bob",
                "StudentAge": 25
            },
            {
                "StudentName": "David",
                "StudentAge": 24
            }
        ]
    }
]);

Example: Get Distinct Student Names

Query to get distinct student names from the nested array ?

db.getDistinctListOfSubDocumentFieldDemo.distinct("StudentPersonalDetails.StudentName");
[ "Carol", "John", "Bob", "David" ]

Verify Sample Data

db.getDistinctListOfSubDocumentFieldDemo.find().pretty();
{
    "_id" : ObjectId("..."),
    "StudentId" : 101,
    "StudentPersonalDetails" : [
        {
            "StudentName" : "John",
            "StudentAge" : 24
        },
        {
            "StudentName" : "Carol",
            "StudentAge" : 21
        }
    ]
}
{
    "_id" : ObjectId("..."),
    "StudentId" : 102,
    "StudentPersonalDetails" : [
        {
            "StudentName" : "Carol",
            "StudentAge" : 26
        },
        {
            "StudentName" : "Bob",
            "StudentAge" : 21
        }
    ]
}
{
    "_id" : ObjectId("..."),
    "StudentId" : 103,
    "StudentPersonalDetails" : [
        {
            "StudentName" : "Bob",
            "StudentAge" : 25
        },
        {
            "StudentName" : "David",
            "StudentAge" : 24
        }
    ]
}

Conclusion

Use distinct() with dot notation to extract unique values from nested array fields. MongoDB automatically flattens arrays and removes duplicates, returning distinct values from all matching sub-documents across the collection.

Updated on: 2026-03-15T00:17:10+05:30

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements