31

I have Author and Book models.

An Author has many embedded Books.

Can I query the embedded Books, or do I have to fetch Authors first to get Books?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
sewid
  • 341
  • 1
  • 3
  • 7

1 Answers1

50

You can query embedded documents, just qualify the name. Now, this will return all Authors that have books that match your query.

If Author is defined as having many :books (and book is an embedded::document)

@authors_with_sewid = Author.where("books.name" => "sewid").all

You'd then need to iterate over the authors and extract the books.

Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109
  • Ok, thanks a lot. What if I have a mixture of embedded and referenced documents, can I also query for referenced documents? For example, the Author model has a creator-field, that contains the ID of an user. Is it possible to do 'Author.where("book.name" = "sewid").and("creator.username" => "example")'? A first try failed. – sewid Oct 18 '10 at 05:21
  • Once they are referenced objects, you would need a Join. And there are no Joins in mongodb land. – Jesse Wolgamott Oct 18 '10 at 12:30
  • 2
    The best thing to do in that case is denormalize your data and store the creator username with the Author. – Nader Nov 01 '10 at 04:21
  • Just a quick notice. It should be ("books.name" => "sewid"), as the author has many embedded books. – Alex Jan 02 '11 at 16:31
  • @JesseWolgamott is it possible to just return the books, and not have to iterate over the authors to extract? – pizza247 Oct 09 '12 at 19:14
  • 1
    Note that more complex queries can still be done, like this: `all_of({:'books.name' => 'name'}, {:'books.author' => /joe/i})` – Peter Ehrlich Nov 13 '12 at 23:53
  • it also works in this format: `('book.name': 'sewid')` – Aboozar Rajabi Apr 23 '19 at 12:25