Mongoid Scope Check If Array Field Contains Value Mongoid Scope Check If Array Field Contains Value mongodb mongodb

Mongoid Scope Check If Array Field Contains Value


You're drastically overcomplicated things. If a field holds an array then you can search it as though it wasn't an array. For example, if you have this in a document:

{ some_array: [ 'where', 'is', 'pancakes', 'house?' ] }

and you do a query like this:

where(:some_array => 'pancakes')

you'll find that document. You don't need $elemMatch or anything complicated here; you can pretend that the array is a single value for simple queries like you have:

scope :some_scope, ->(value) { where(:some_array => value) }

You only need to get into $elemMatch if you want to apply multiple conditions to each element of the array, things like this from the $elemMatch docs:

   results: { $elemMatch: { $gte: 80, $lt: 85 } }// ^^^^^^^array           ^^^^^^^^^^^^^^^^^^^^^multiple conditions

Don't feel bad, the current MongoDB docs aren't exactly clear on this stuff (or at least I can't find an explicit explanation).