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']
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;
You can do this with distinct:
db.foo.distinct('friends.two')
Output:
[
"b",
"d",
"f"
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With