Tim Tim - 4 months ago 74
Node.js Question

mongoose $aggregation $match $or between dates

I want to filter like this in an aggegration. Here is an example of mongoose query. The same thing i want to do in an aggegration. What i want to do is get all measurements between 2016-06-01T22:52:46Z and 2016-06-02T22:52:46Z and the other values

Measurement
.find({})
.or([{
'date': {
'$gte': ISODate('2016-06-01T22:52:46Z'),
'$lte': ISODate('2016-06-02T22:52:46Z')
}
}, {
'date': {
'$gte': ISODate('2016-06-10T22:52:46Z'),
'$lte': ISODate('2016-06-11T22:52:46Z')
}
}, {
'date': {
'$gte': ISODate('2016-06-14T22:52:46Z'),
'$lte': ISODate('2016-06-15T22:52:46Z')
}
}, {
'date': {
'$gte': ISODate('2016-06-26T22:52:46Z'),
'$lte': ISODate('2016-06-27T22:52:46Z')
}
}])
.exec();


This is what i tried but it didn't do the same job. And the IDE says dublicated keys 'date'

db.measurements.aggregate([{
$match: {
$or: [{
date: {
'$gte': ISODate('2016-06-01T22:52:46Z'),
'$lte': ISODate('2016-06-02T22:52:46Z')
},
date: {
'$gte': ISODate('2016-06-10T22:52:46Z'),
'$lte': ISODate('2016-06-11T22:52:46Z')
},
date: {
'$gte': ISODate('2016-06-14T22:52:46Z'),
'$lte': ISODate('2016-06-15T22:52:46Z')
},
date: {
'$gte': ISODate('2016-06-26T22:52:46Z'),
'$lte': ISODate('2016-06-27T22:52:46Z')
}
}]
}
}]);

Answer

Do you have some example of data? Try this code:

db.measurements.aggregate([{
  $match: {
    $or: [
    { date: {
        '$gte': ISODate('2016-06-01T22:52:46Z'),
        '$lte': ISODate('2016-06-02T22:52:46Z')
      }},
      { date: {
        '$gte': ISODate('2016-06-10T22:52:46Z'),
        '$lte': ISODate('2016-06-11T22:52:46Z')
      }},
      { date: {
        '$gte': ISODate('2016-06-14T22:52:46Z'),
        '$lte': ISODate('2016-06-15T22:52:46Z')
      }},
      { date: {
        '$gte': ISODate('2016-06-26T22:52:46Z'),
        '$lte': ISODate('2016-06-27T22:52:46Z')
      }}
    ]
  }
}]);
Comments