MongoDB:如何获取子文档字段值的不同列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16155266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:09:52  来源:igfitidea点击:

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

mongodbdistinctnosql

提问by vladimir

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.

结果的结构可能不同。如何在 MongoDB 中实现这一目标?应该很简单,但我无法弄清楚。我在集合上尝试了 aggregate() 函数,但后来我不知道如何应用 distinct() 函数。

回答by Asya Kamsky

You can just do:

你可以这样做:

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

In your case it returns:

在您的情况下,它返回:

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

回答by Vladimir Muzhilov

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}}}])