如何从mongodb中的字段中的对象数组中检索部分对象 [英] how to retrieve partial objects from object array in a field in mongodb
本文介绍了如何从mongodb中的字段中的对象数组中检索部分对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个猫鼬模式-
db.foo.insert({one:'a',friends:[{two:'b',three:'c'},{two:'d',three:'e'},{two:'f',three:'G'}]})
现在我想要的是两个仅检索friends
数组的'two'
部分
那就是我想在friends
数组的每个对象中找到所有two
值的数组
在mongodb中这样的投影是否可能,其中输出看起来像-
now what i want is two retrieve only the 'two'
part of friends
array
that is I want to find an array of all the values of two
in each object in friends
array
Is such a projection possible in mongodb where in the output looks like -
['b','d','f']
推荐答案
aggregate
是您的答案
db.foo.aggregate({"$project" : {"two" : "$friends.two"}}).result
还有另一种方法(获取不同的值)
there is another way to do that (getting distinct values)
db.foo.aggregate([
{'$project': {
union:{$setUnion:["$friends.two"]}
}
}
]).result;
这篇关于如何从mongodb中的字段中的对象数组中检索部分对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文