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

回眸只為那壹抹淺笑 提交于 2019-12-23 20:55:06

问题


I have a mongoose schema like -

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

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']

回答1:


aggregate is your answer

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;



回答2:


You can do this with distinct:

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

Output:

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


来源:https://stackoverflow.com/questions/27606591/how-to-retrieve-partial-objects-from-object-array-in-a-field-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!