MongoDB: How to get distinct list of sub-document

2020-02-02 11:32发布

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.

2条回答
Lonely孤独者°
2楼-- · 2020-02-02 12:06

You can just do:

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

In your case it returns:

[ "John", "Anna", "Kevin" ]
查看更多
看我几分像从前
3楼-- · 2020-02-02 12:06

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}}}])
查看更多
登录 后发表回答