Time Gt Query Not Working with Mongoid and Ruby on Rails

Mongoid: Type of timestamps strings?

Does your model contain a

include Mongoid::Timestamps

If it is, someObject.created_at.class should return Time

See http://mongoid.org/en/mongoid/docs/extras.html#timestamps

Mongoid date range query

There was a bug in Mongoid. Fixed now.

For more information:

https://github.com/mongoid/mongoid/issues/761

https://github.com/mongoid/mongoid/commit/f326de5acc969e1342e640dc026de7e94bf4cf49#lib/mongoid/matchers.rb

Mongoid queries are fast but converting to results takes time

I haven't look at the source code yet, but Mongoid queries are lazily evaluated.

Which means, your first call to the criteria does not touch the database, and Mongoid actually really fetch the data when you do 'to_a' or 'entries' hence the time lag.

How to do mongoid 'not_in' 'greater than' query

model without attribute greater than 100 = model with attribute less than or equal to 100?

Model.where({'price' => {'$lte' => 100}})

Date Querying in Mongoid

This is a known bug in Mongo. See ISSUE 405

The reason is that Mongo uses an unsigned number to store dates, so anything before the epoch rolls over far into the future.

Affortunately this issue has been fixed for stable version 2.0 released today. Upgrading to this version should solve your problem.

Mongoid Syntax for running range queries with or condition

When you say:

:range_field.lte => some_date_time

you're calling a method, lte, that Mongoid monkey patches in Symbol. That method returns an Origin::Key instance that is wrapped around the underlying $lte operator. Somewhere inside Mongoid that Origin::Key will be converted to something that MongoDB will understand:

{ range_field: { $lte: some_date_time } }

If you look at what

where(:range_field.lte => t1, :range_field.gte => t2)

becomes by calling selector on the result, you'll see something like this:

{
"created_at" => {
:$gte => t2,
:$lte => t1
}
}

and everything will work fine.

However, if we use #or and call selector to see the underlying query, we see that Mongoid is expanding the Origin::Keys one by one and merging the results:

or({:range_field.lte => t1, :range_field.gte => t2})
# is expanded as though as you said
or({ :range_field => { :$lte => t1 }, :range_field => { :$gte => t2 } })
# which is the same as
or({ :range_field => { :$gte => t2 } })

Essentially, Mongoid is being inconsistent as to how it expands the Origin::Keys. You'll even get the same confusing result if you use :$or instead of #or:

where(:$or => [ {:range_field.lte => t1, :range_field.gte => t2} ]).selector

will say:

{ "$or" => [ { "range_field" => { "$gte" => t2 } } ] }

The solution is to not use the Symbol monkey patched methods and do that part by hand:

or(
{ :range_field => { :$lte => t1, :$gte => t2 } },
{ :range_field => { :$lte => t3, :$gte => t4 } },
...
)


Related Topics



Leave a reply



Submit