Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid / Mongodb and querying embedded documents

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?

like image 888
sewid Avatar asked Oct 17 '10 18:10

sewid


People also ask

How do I query embedded files in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

What is embedded document in MongoDB?

MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document.

How do I query a document in MongoDB?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.


1 Answers

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.

like image 137
Jesse Wolgamott Avatar answered Sep 23 '22 04:09

Jesse Wolgamott