corvid
corvid

Reputation: 11187

find document in today's date range in mongodb

I have a collection, Plans. I want to find everything within the range of one month. Here is a sample of what the data could look like:

{
  "_id": "someid",
  "dateStart": ISODate("2015-03-01T00:00:00Z"),
  "dateEnd": ISODate("2015-03-31T00:00:00Z"),
  "items": [
    "someotherid"
  ]
}

How can I find the Plan such that today's date is between dateStart and dateEnd?

Upvotes: 1

Views: 2008

Answers (2)

David Weldon
David Weldon

Reputation: 64312

date1 = new Date('3/1/15');
date2 = new Date('4/1/15');

Plans.find({
  startDate: {$gte: date1},
  endDate: {$lt: date2}
});

New Date objects initialize to 00:00:000 so you can use that to your advantage here. Also note that "less than 4/1" is equivalent to "less than or equal to midnight on 3/31" - but the former is much easier to write.

Also note that moment is a super handy utility for doing manipulations like this. For example: moment().endOf('month').toDate()

To add the package just do:

$ meteor add momentjs:moment

Upvotes: 2

chridam
chridam

Reputation: 103375

To find a Plan such that today's date is between the dateStart and dateEnd fields, create a date object that holds the current date then use the $lt and $gt query operators on the date fields to query documents where today's date falls between the two fields:

currentDate = new Date();
Plans.find({
    dateStart: { $lt: currentDate },
    dateEnd: { $gt: currentDate }
});

Upvotes: 2

Related Questions