Doug English
Doug English

Reputation: 286

Finding documents containing at least one embedded object missing a given field

Is there an efficient way to find all documents of a Mongo collection that have at least one embedded object missing a given field?

I'm trying:

Response.where('answers.question_id' => nil)

However, this only returns Responses for which every answer is missing a question_id, rather than responses that contain at least one answer missing a question_id.

I could loop through the Responses testing each, but this is horrendously slow for the size of the database I'm working with, so I'm keen to find a way to construct a query to narrow the response list.

EDIT:

Response.where(:'answers.question_id'.exists => false)

Still does not solve my problem - it still only finds responses for which all embedded answers are missing question_id, not responses for which any embedded answers are missing question_id.

Upvotes: 1

Views: 102

Answers (1)

jimoleary
jimoleary

Reputation: 1645

Have you tried either of the following?

Response.where(:answers => { "$elemMatch" => { :"answer_id".exists => false }})
Response.where(:answers.elem_match => { :answer_id.exists => false})

Upvotes: 1

Related Questions