views:

72

answers:

1

Hi,

I have an Author model and a Book model.

When the Author has many embedded Books, is it possible to query for all Books in mongoid (rails 3.0.1) or do I always have to fetch the Author to get the Books?

Best regards, sewid

A: 

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("book.name" => "sewid").all

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

Jesse Wolgamott
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
Once they are referenced objects, you would need a Join. And there are no Joins in mongodb land.
Jesse Wolgamott