简体   繁体   中英

Query by date i mongo from node.js

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....

Please consider that by default the date operation in Mongo are in UTC, eg 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-22T 13: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")} })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM