Wetrue
Wetrue

Reputation: 61

Mongoose query date time between

Hi pls help me to solve this issue

I need to query data on date time between on Mongoose 2016-09-25T00:00:10.000+07:00 to 2016-09-25T01:00:10.000+07:00

on robomongo i use this query it's working find

db.getCollection('positions').find({unit_id:"863835025684908",
utc_ts : {
    $gte: ISODate("2016-09-25T00:00:10.000+07:00"),
    $lt:  ISODate("2016-09-25T01:00:10.000+07:00")  
    } 
})

I got result

{
"_id" : ObjectId("57e6bd10fa10a661c4145870"),
"updated_at" : ISODate("2016-09-25T00:51:12.673+07:00"),
"created_at" : ISODate("2016-09-25T00:51:12.673+07:00"),
"unit_id" : "863835025684908",
"utc_ts" : ISODate("2016-09-25T00:51:10.000+07:00"),
"recv_utc_ts" : ISODate("2016-09-25T00:51:12.000+07:00"),
"lat" : 14.127961,
"lon" : 100.621365
}

But when I query on mongoose I use this

var startDate = moment(req.params.startTime).add('hours',7); //req.params.startTime = 2016-09-25 00:00:00
var endDate   = moment(req.params.endTime).add('hours',7); //req.params.endTime = 2016-09-25 01:00:00

//Find 
Positions.find({
    unit_id: req.params.unit_id,
    utc_ts: {
        $gt:  new Date(startDate).toISOString(),
        $lt:  new Date(endDate).toISOString()
    }
}, function(err, positions) {
    if (err) {
        return err
    }
    else {
        //console.log(positions);
        res.json(positions);
    }
});

I see mongoose debug show

Mongoose: positions.find({ utc_ts: { '$gt': new Date("Sat, 24 Sep 2016 00:51:10 GMT"), '$lt': new Date("Sat, 24 Sep 2016 01:08:36 GMT") }, unit_id: '863835025684908' }, { fields: undefined })

Then I got empty array from query

Upvotes: 5

Views: 34080

Answers (2)

Miko Chu
Miko Chu

Reputation: 1392

Here you go using vanilla Node, to get all of the positions for the date 2021-07-09.

Positions.find({
 utc_ts: {
  $gte: new Date('2021-07-09T00:00:00Z'),
  $lt: new Date('2021-07-10T00:00:00Z') // +1 day
 }
})

For a date range from 2021-07-09 to 2021-07-11, do the ff (just add +1 day):

Positions.find({
 utc_ts: {
  $gte: new Date('2021-07-09T00:00:00Z'),
  $lt: new Date('2021-07-12T00:00:00Z') // +1 day
 }
})

Upvotes: 3

Arif Khan
Arif Khan

Reputation: 5069

I don't think you need to use Date object. You may like to use format() function of momentjs. Here would code to fetch positions

var startDate = moment(req.params.startTime).utcOffset('+0700').format("YYYY-MM-DDTHH:mm:ss.SSSZ"); //req.params.startTime = 2016-09-25 00:00:00
var endDate   = moment(req.params.endTime).utcOffset('+0700').format("YYYY-MM-DDTHH:mm:ss.SSSZ"); //req.params.endTime = 2016-09-25 01:00:00

//Find 
Positions.find({
    unit_id: req.params.unit_id,
    utc_ts: {
        $gt:  startDate,
        $lt:  endDate
    }
}, function(err, positions) {
    if (err) {
        return err
    }
    else {
        //console.log(positions);
        res.json(positions);
    }
});

Upvotes: 5

Related Questions