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
?
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.
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.
The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With