0

I am a beginner in mogo and mongoid. I it possible to filter sub-documents collection by a sub-sub-documents multiple fields ($elemMatch)? I'm trying to make a parametrized scope for an embedded collection.

Set up:

class Product
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String, default: ''

  embeds_many :versions, class_name: self.name, validate: false, cyclic: true
  embeds_many :flags
end

class Flag
  include Mongoid::Document
  include Mongoid::Timestamps

  field :text, type: String
  field :state, type: Boolean
end

Typically now i want to filter my versions within single product by flags state and name:

Product.first.versions.where('$elemMatch' => {'flags.text' => 'normalized', 'flags.state' => true}) dosn't work.

Either don't work:

Product.first.versions.elem_match(flags: {text: 'normalized', state: true})
Product.first.versions.where(:flags.elem_match => {text: 'normalized', state: true})
Product.first.versions.where(flags: {'$elemMatch' => {text: 'normalized', state: true}})

Is there a way to do this? Thanks.

  • by the docs : http://mongoid.org/en/origin/docs/selection.html#docs, This : Product.first.versions.elem_match(flags: {text: 'normalized', state: true}) should work, but try also Product.first.versions.where(flags => {'$elemMatch' => {text => 'normalized', state => true}}). Have you tried to make the query in the mongoshell? Would help much if you could provide the right (that you likely to use in mongoid) query in mongoshell format. – attish Jun 07 '13 at 09:57
  • I don't know how to reproduce this in mongo shell.. According to log Mongoid makes single query to fetch the whole document `Product.first` and then emulates query on an embedded collection, without actually hitting the database. However something like `Product.first.versions.where('flags.text' => 'normalized')` works just fine, returning an array with corresponding versions. It only doesn't work when i want to filter the embedded collection by multiple sub-sub-documents field – SilentShade Jun 07 '13 at 11:54
  • Corresponding issue in mongoid/mongoid https://github.com/mongoid/mongoid/issues/3097 – SilentShade Jun 11 '13 at 12:15

0 Answers0