How to get partial objects from an array of objects into a field in mongodb

I have a mongoose schematic like -

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

      

now what i want is to get only a part of the 'two'

array friends

i.e. i want to find an array of all values two

in each object in the array friends

Is such a projection possible in mongodb where the output looks like -

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

      

+3


source to share


2 answers


aggregate

- your answer

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

      



there is another way to do this (getting individual values)

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

      

+4


source


You can do it with distinct

:

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

      



Output:

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

      

+4


source







All Articles