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