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

编程入门 行业动态 更新时间:2024-10-18 05:59:38
本文介绍了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");

在你的情况下它返回:

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

更多推荐

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

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

发布评论

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

>www.elefans.com

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