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

vladimir picture vladimir · Apr 22, 2013 · Viewed 22.8k times · Source

Let's say I have the following documents in collection:

{
   "family": "Smith",
   "children": [
        {
            "child_name": "John"
        },
        {
            "child_name": "Anna"
        },
    ]
}

{
   "family": "Williams",
   "children": [
        {
            "child_name": "Anna"
        },
        {
            "child_name": "Kevin"
        },
    ]
}

Now I want to get somehow the following list of unique child names cross all families:

[ "John", "Anna", "Kevin" ]

Structure of result might be different. How to achieve that in MongoDB? Should be something simple but I can't figure out. I tried aggregate() function on collection but then I don't know how to apply distinct() function.

Answer

Asya Kamsky picture Asya Kamsky · Apr 22, 2013

You can just do:

db.collection.distinct("children.child_name");

In your case it returns:

[ "John", "Anna", "Kevin" ]