4

I want to query mongo collection by date. Example:

var startDate = new Date(dateNow.getUTCFullYear(),dateNow.getUTCMonth(),dateNow.getUTCDate(),dateNow.getUTCHours(),0);
    var endDate = new Date(dateNow.getUTCFullYear(),dateNow.getUTCMonth(),dateNow.getUTCDate(),dateNow.getUTCHours()+1,0);

query.timeRegistered = { '$gte' : startDate, '$lt' : endDate };

... make mongo query ... 

But it doesn't work. I assume that is because mongo saves date object in ISODate format. This query works from shell because there mongo converts Date to ISODate but from javascript (node.js) it doesn't work. I've tried all possible solutions but neither of them helped me.

Please, if anyone has any solution I would be very gratefull....

Ivan Longin
  • 3,207
  • 4
  • 33
  • 42
  • 1
    Using Javascript `Date` objects in your node.js mongo query object is the correct approach. Can you show more of your code? – JohnnyHK Oct 12 '12 at 15:09
  • 1
    please define "does not work" - do you get an error? Do you get no documents returned? – Asya Kamsky Oct 12 '12 at 20:49
  • The date range should be ok. Your problem might be something else. See the related question: http://stackoverflow.com/questions/11973304/mongodb-mongoose-querying-at-a-specific-date – Trantor Liu Jul 01 '13 at 08:13

1 Answers1

0

Please consider that by default the date operation in Mongo are in UTC, e.g. I entered the record in "t1" collection at June 22nd 2015 at 7:10 PM IST. however, in the shell you can see its value as 'ISODate("2015-06-22T13:40:08.545Z")' which is 5:30 hours behind. from your javascript code (which is run on the browser and hence take the browser timezone) try to create the start and end date variables as per the UTC timezone and then query the records. Let us know if it does't work, to keep it simple, give a very large date range and see if its working or not. as I am not a JS expert, I assume you may need to adjust your dates to make it in UTC.

however, tried with the Mongo client as below and it worked so I assume from JS also it should work as long you pass the date in right timezone.


db.t1.find({dt:{$gt:ISODate("2015-06-22T13:40:00.000Z"),$lt:ISODate("2015-06-22T13:41:00.000Z")} })
Sachin Shukla
  • 173
  • 10