2

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?

3 Answers 3

11

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}});
Sign up to request clarification or add additional context in comments.

4 Comments

How could I create endTime based on startTime?
@Erik You could increment the day of a date by using somedate.setDays(someDate.getDays() + 1). And yes, this works across month-boundaries. Trying to set the date to January 32nd sets it to February 1st. More about node.js and date manipulation in this blog article.
Thanks! and how could I ignore time?
@Erik You can't. A Date object always represents a specific point in time, accurately to the millisecond. A day is a 24 hour time period. A time period is defined by a start-date and an end-date. When you want to select all dates in a given 24 hour time period, you need to query all dates larger than the beginning and less than the end of that time period.
0

You need to create Date objects this should help

var start = new Date(2010, 3, 1);
var end = new Date(2010, 4, 1);

http://cookbook.mongodb.org/patterns/date_range/

4 Comments

But I have only startTime.
db.collection.find({startTime: {$eq: new Date("2014-05-19T20:30:00.000Z")}});
I get the following error: "Can't use $eq with Date."
try it like this db.collection.find({"createdAt" : new Date("2014-05-19T20:30:00.000Z") }); from here stackoverflow.com/questions/8835757/return-query-based-on-date
0

You can store a number in a field with a inverted date. So, for a date like 2023-06-08 you should store the number 20230608. This way, you can search using the following query:

db.collection.find({ startTime: 20230608 })

This method is much easier than using dates and improves database performance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.