2

I'm trying query between two dates in MongoDB but I'm not getting anything back but I do have the correct data. I'm thinking that the date format might be wrong. Is it correct?

This is the query that I'm running

  { '$gte': Sun Feb 01 2015 02:00:00 GMT+0200 (IST),
      '$lt': Tue Mar 03 2015 02:00:00 GMT+0200 (IST) }

and my JS query code looks like this

query.created = {$gte:new Date(this.props.startDate), $lt:new Date(this.props.endDate)};
Almog
  • 2,639
  • 6
  • 30
  • 59
  • did you check [this SO](http://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb)? – Ethaan Feb 19 '15 at 22:06
  • 1
    @Ethaan no going over it now looks like the wrong format thanks – Almog Feb 19 '15 at 22:07
  • Be careful not to mix up the mongo shell and meteor here... The JS code you posted doesn't look bad (Meteor uses the JS `Date` object everywhere). I don't understand what the first object is (it's not even valid JSON).. – mnemosyn Feb 19 '15 at 22:08
  • @mnemosyn is the console.log for the query created – Almog Feb 19 '15 at 22:19

3 Answers3

5

Mongo recognizes the ISODate type. It can be used to make common date-related queries (like the one you're trying to do).

So it should be something like this:

{ '$gte': ISODate(01-02-2015T02:00:00Z),
  '$lt': ISODate(03-03-2015T02:00:00Z) }

Please read further this documentation for more details.

Also, check out this link to the oficial online courses, there is a section where it cover your problem.

chomsky
  • 300
  • 3
  • 13
  • 2
    AFAIK, `ISODate` is part of the mongo console and isn't known to Meteor – mnemosyn Feb 19 '15 at 22:20
  • Woa! I didn't see the meteor tag, sorry about that, like you're saying, this answer was to deal with the mongo console. Should I delete the answer? – chomsky Feb 19 '15 at 22:48
2
db.collection.find({
    created_at: {
        $gte: ISODate("2015-02-01T00:00:00.000Z"),
        $lt: ISODate("2015-03-03T00:00:00.000Z")
    }
})
0

I use twix.js and publish my collection for responses in an array that match my date-range condition.

Dave
  • 433
  • 3
  • 9