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.

Solution 1

You can just do:

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

In your case it returns:

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

Solution 2

with the help aggregation framework:

db.collection.aggregate([{$unwind:'$children'}, {$group:{_id:'$children.child_name'}}])

or more interest ;) with frequency of name:

db.collection.aggregate([{$unwind:'$children'}, {$group:{_id:'$children.child_name', freq:{$sum:1}}}])