本文介绍了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:如何获取子文档字段值的不同列表?
发布评论