Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if an embedded document exists in a document in mongoid?

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!

like image 526
Goalie Avatar asked May 10 '12 03:05

Goalie


People also ask

How do I access an embedded document 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 an 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.

What is an embedded 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).

How do I search for an object in MongoDB?

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.


1 Answers

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.

like image 141
SteveO7 Avatar answered Sep 27 '22 21:09

SteveO7