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.
You can just do:
db.collection.distinct("children.child_name");
In your case it returns:
[ "John", "Anna", "Kevin" ]