How does MongoDB compares the date only and ignores the time, such as date <= '2010-09-10'?
For some reason:
Analytic.where({:ga_date.gte => '2010-09-01'}).count() # greater than or equal to
gives back 0, but
Analytic.where({:ga_date.gte => Time.parse('2010-09-01')}).count()
gives back 230, which is the number of records (documents).
Actually, the first line on the top works in another case, so it is quite strange.
Can only the date be compared, because if it is
Analytic.where({:ga_date.lte => Time.parse('2010-09-10')}).count() # less than or equal to
then all the records with date 2010-09-10 will not be counted because Time.parse('2010-09-10') will give 2010-09-10 00:00:00, so the records will all have to be 2010-09-09 before the midnight. In other words, 2010-09-10 2am won't be included because 2am is not "less than or equal to" 00:00:00. It can be hacked by using
Analytic.where({:ga_date.lte => Time.pa开发者_JAVA百科rse('2010-09-10 23:59:59')}).count()
but it is kind of ugly. If there is a way to compare by date only like the first line of code in this post?
I think that you have two separate issues here.
Different data types
The following two lines are not equivalent. The first is a string comparison. The second is a comparison with a date object.
Analytic.where({:ga_date.gte => '2010-09-01'}).count()
Analytic.where({:ga_date.gte => Time.parse('2010-09-01')}).count()
I think you have figured this out, but it's important to be clear here. If you are storing date objects in the DB, you need to perform comparisons with date objects.
MongoDB will compare types and data.
Mismatch date storage
You are storing dates that have information for hours, minutes and seconds. However, you don't like the following notation:
:ga_date.lte => Time.parse('2010-09-10 23:59:59')
The workaround here is to use $lt
and the day after.
:ga_date.lt => (Time.parse('2010-09-10') + 1.day) # or (60 * 60 * 24)
to add, it is not strangely works, its coincidentally works when it just happens the string representation of the date happens to also lexicographically be 'greater than' the other date
other issue, try to use only as much data fields as needed
if you meant it to be "within the calendar day", what I usually like is to call beginning_of_day in both cases to equalize this has the effect of neutralizing the minutes
else if you really meant within a 24h strike zone, use ActiveSupport's '+ 1.day'
精彩评论