0

I have a document structure in MongoDB like this:

User
 |---> Posts
        |----> Comments

So, a parent document User with a collection of embedded Post documents, which itself has a collection of embedded Comment documents.

I grab the User document back and now have the entire document tree in memory, like so:

user = User.where(username: 'test').first

From user how can I get a list of all the comments?

1 Answer 1

1

Try something like this:

user.posts.map{|p| p.comments}.flatten

Or

user.posts.flat_map(&:comments)
7
  • Thanks – I had to change it to user.posts.map {|p| p.comments}.flatten, and that now works as expected.
    – Martin
    Jan 6, 2012 at 23:01
  • @Martin: yes, sorry, that was my bad. But I'm glad it helped :-) Jan 6, 2012 at 23:02
  • You can do: user.posts.map(&:comments).flatten Aug 24, 2015 at 9:42
  • Do you know how can I make flatten, and still 'query' the result? in flatten we get the results as array, so it failed undefined method where for #<Array:0xd790664> Aug 24, 2015 at 9:49
  • @user2503775: you'd have to go another way: Comment.where(:post_id.in => [user.posts.distinct(:id)]).where(...) Aug 24, 2015 at 9:52

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.