ruby on rails - Nested Querying in Mongoid in 2013 -
so question 2 years old:
querying embedded objects in mongoid/rails 3 ("lower than", min operators , sorting)
and way recommends query nested objects less or greater than:
current_user.trips.where('start.time' => {'$gte' => time.now}).count
simply doesn't work, returns 0 numerous queries have wrong. i've tried
current_user.trips.where(:'start.time'.gte => time.now}).count
which 0. none of these throw error.
what correct syntax querying nested elements nowadays? seems fair bit of confusion on this.
it works expect in environment. (mongoid 3.1.3)
class user include mongoid::document embeds_many :trips end class trip include mongoid::document embeds_one :start embedded_in :user end class start include mongoid::document field :time, type: datetime embedded_in :trip end user.create({ trips: [ trip.new({ start: start.new({ time: 5.days.ago }) }), trip.new({ start: start.new({ time: 2.days.from_now }) }) ] }) current_user = user.where({}).first p current_user.trips.where('start.time' => {'$gte' => time.now}).count p current_user.trips.where(:'start.time'.gte => time.now).count
the above code outputs following:
1 1
is $gte
correct? common mistake use opposite sign when comparing dates.
or might because using older version of mongoid.
update:
you can check queries mongoid generates following code:
mongoid.logger.level = logger::debug moped.logger.level = logger::debug mongoid.logger = logger.new($stdout) moped.logger = logger.new($stdout)
this useful debugging.
Comments
Post a Comment