3

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']
2
  • @JohnnyHK I just edited the question to include the expected answer. Commented Dec 22, 2014 at 16:44
  • No, they are unique values. I am inserting that way only. Sorry forgot to mention that earlier Commented Dec 22, 2014 at 16:50

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

4

You can do this with distinct:

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

Output:

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

1 Comment

It says Error:Distinct is not implemented. in the try.mongodb.org. but worked fine on my desktop. Thanks for the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.