Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query documents by Date in MongoDB?

My events colleciton stores the following documents:

{
  "_id": {
      "$oid": "537b2a232a47f21830ae5b7b"
  },
  "startTime": {
      "$date": "2014-05-18T21:00:00.000Z"
  },
  "endTime": {
      "$date": "2014-05-18T23:00:00.000Z"
  }
},
{
  "_id": {
    "$oid": "537af8136c4162d0379e2139"
  },
  "startTime": {
    "$date": "2014-05-19T20:30:00.000Z"
  },
  "endTime": {
    "$date": "2014-05-19T21:30:00.000Z"
  }
}

How could I query events by specific startTime in like the following:

var startTime = '2014-05-18T20:00:00.000Z';

db.collection.find({startTime: {$eq: startTime}});

My problem is I need ignore time and use only date in the query. How could I construct my query?

like image 886
Erik Avatar asked Dec 12 '25 23:12

Erik


1 Answers

Define a date at midnight of the day you want to query and at midnight of the following day. Then use the $lt (less-than) and $gt (greater-than) operators to get all results in the timespan between these two points in time.

var from = new Date('2014-05-18T20:00:00.000Z');
var to = new Date('2014-05-19T20:00:00.000Z');

db.collection.find({startTime: {$gt: from, $lt:to}});
like image 101
Philipp Avatar answered Dec 15 '25 13:12

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!