Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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']
like image 589
Harshit Laddha Avatar asked Dec 05 '25 10:12

Harshit Laddha


2 Answers

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;
like image 86
2 revs, 2 users 67% Avatar answered Dec 07 '25 10:12

2 revs, 2 users 67%


You can do this with distinct:

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

Output:

[
  "b",
  "d",
  "f"
]
like image 29
JohnnyHK Avatar answered Dec 07 '25 10:12

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!