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

编程入门 行业动态 更新时间:2024-10-18 03:34:14
本文介绍了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:如何获取不同的子文档字段值列表?

本文发布于:2023-11-22 13:41:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   文档   列表   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!