MongoDB:如何获取不同的子文档字段值列表? [英] MongoDB: How to get distinct list of sub-document field values?

查看:82
本文介绍了MongoDB:如何获取不同的子文档字段值列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我收集了以下文件:

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" ]

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

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.

推荐答案

只需这样做:

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

在您的情况下,它返回:

In your case it returns:

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

这篇关于MongoDB:如何获取不同的子文档字段值列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆