繁体   English   中英

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

[英]how to retrieve partial objects from object array in a field in mongodb

我有一个猫鼬模式 -

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

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

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

aggregate是你的答案

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

还有另一种方法(获得不同的值)

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

您可以使用distinct来执行此操作:

 db.foo.distinct('friends.two')

输出:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM