How do you check if an embedded document exists for a document using mongoid in Ruby on Rails? Say I have a document user
that has name
, email
, and might have a nicknames
embedded document. Right now if I run user.first.nicknames
and if that user
doesn't have the nicknames
embedded document in it, it will error out. I've tried matches?
and exists?
but they don't work.
Thanks!
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.
An embedded document is when one document (often a structured text file, or a binary, or anything else) is embedded within another. (This discussion assumes that the result is a linear sequence of bytes/characters--use of more advanced filing systems is beyond the scope of this discussion).
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object. Here is the query to search in an array of objects in MongoDB.
With a little help from the other answers here, I found something that worked for me and I think this is what the original poster had in mind;
Model.where(:"subdoc.some_attribute".exists => true)
This will return all documents where the "some_attribute" exists on the subdocument. Notice the syntax of the symbol, that's what I was missing.
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