0

I m trying to query my collection by a range of date. I m trying to use ISODate in the query passing a javascript date and it doesn't work, and I dont know why...

I have tried :

db.collection.aggregate {date: {$gt: 'new Date(' + start.toISOString() + ')', $lt: 'new Date(' + end.toISOString() + ')'}}, {"$group": {_id: "$user", count: {$sum: 1}}}

db.collection.aggregate {date: {$gt: 'ISODate(' + start.toISOString() + ')', $lt: 'ISODate(' + end.toISOString() + ')'}}, {"$group": {_id: "$user", count: {$sum: 1}}}

db.collection.aggregate {date: {$gt: 'ISODate(' + start + ')', $lt: 'ISODate(' + end + ')'}}, {"$group": {_id: "$user", count: {$sum: 1}}}

db.collection.aggregate {date: {$gt:start, $lt: end}}, {"$group": {_id: "$user", count: {$sum: 1}}}

Nothing works...

Can you help me ? Or explain me why it doesn't work in each case ?

mfrachet
  • 8,772
  • 17
  • 55
  • 110
  • possible duplicate of [MongoDB/Mongoose querying at a specific date?](http://stackoverflow.com/questions/11973304/mongodb-mongoose-querying-at-a-specific-date) – RickyA Oct 20 '14 at 14:55

1 Answers1

1

Why do you put Date constructors as strings and concatenate it with start, end values? Comparing Date objects to strings like "new Date(2014-10-20T15:27:24.110Z)" is not gonna work for sure.

If start, end are plain JavaScript Date objects, you can construct the ISODate objects for comparison using the ISODate helper like so:

db.collection.aggregate([
    {$match: {date: {
        $gt: ISODate(start.toISOString()),
        $lt: ISODate(end.toISOString())
    }}},
    {$group: {_id: "$user", count: {$sum: 1}}}
])
famousgarkin
  • 13,687
  • 5
  • 58
  • 74