如何从MongoDB中的对象数组字段中检索部分对象

3

I have a mongoose schema like -

db.foo.insert({one:'a',friends:[{two:'b',three:'c'},{two:'d',three:'e'},{two:'f',three:'G'}]})

现在我想要的是只检索friends数组中'two'部分, 也就是说,我想找到每个对象中two的所有值的数组。 在mongodb中是否可能进行这样的投影,使输出看起来像-

['b','d','f']

@JohnnyHK 我刚刚编辑了问题,包括了期望的答案。 - Harshit Laddha
不,它们是唯一的值。我只是以那种方式插入。抱歉之前忘记提到了。 - Harshit Laddha
2个回答

4

聚合是你的答案

db.foo.aggregate({"$project" : {"two" : "$friends.two"}}).result

还有一种方法可以做到这一点(获取不同的值)。

db.foo.aggregate([      
    {'$project': {  
                    union:{$setUnion:["$friends.two"]}
                 }
    }
]).result;

4
您可以使用 distinct 实现此操作:
 db.foo.distinct('friends.two')

输出:

[
  "b",
  "d",
  "f"
]

在try.mongodb.org上显示错误:Distinct未实现。但在我的桌面上运行正常。谢谢答案。 - Harshit Laddha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接