9

I have the following collection:

db.sponsoreds.insert([
{
    _id: 1,
    bannerPath: "dms1.jpg",
    startDate: new Date("December 12, 2015 12:00:00"),
    endDate: new Date("November 13, 2016 00:00:00")
},
{
    _id: 2,
    bannerPath: "dms2.jpg",
    startDate: new Date("January 12, 2015 12:00:00"),
    endDate: new Date("January 13, 2016 00:00:00")
},
{
    _id: 3,
    bannerPath: "dms3.jpg",
    startDate: new Date("November 12, 2017 12:00:00"),
    endDate: new Date("November 13, 2018 00:00:00")
 },
 {
 _id: 4,
 bannerPath: "grs1.jpg",
 startDate: new Date("February 01, 2016 12:00:00"),
 endDate: new Date("February 28, 2016 00:00:00")
}
])

How do i query for documents that today is between their start and end dates?

EDIT: This is not a duplication to the suggested "already-asked-question" since:

I'm asking about whether Today is between 2 dates in the document and not whether a date in the document is between 2 dates.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
TBE
  • 1,002
  • 1
  • 11
  • 32
  • 2
    Possible duplicate of [Find objects between two dates MongoDB](http://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb) – Blakes Seven Feb 01 '16 at 09:49
  • 1
    @BlakesSeven Its not a duplicate since I'm asking about whether Today is between 2 dates in the document and you suggested duplication is asking about whether a date in the document is between 2 dates. – TBE Feb 01 '16 at 10:17
  • 1
    And yet your accepted answer uses exactly the same logic as specified. Also noting that the `$and` is not required there as all MongoDB query conditions are already "and" conditions. So "one field" or "two fields" does not matter. The point is to "use range operators". – Blakes Seven Feb 01 '16 at 10:32
  • @BlakesSeven thanks for the explanation, can you post your answer as well so other people and myself will benefit from it? – TBE Feb 01 '16 at 17:43

1 Answers1

14
db.sponsoreds.find({$and:[{startDate:{$lte:new Date()}},{endDate:{$gte:new Date()}}]})

Will return

{
        "_id" : 1,
        "bannerPath" : "dms1.jpg",
        "startDate" : ISODate("2015-12-12T17:00:00Z"),
        "endDate" : ISODate("2016-11-13T05:00:00Z")
}

when run today at 2016-02-01T10:01:41.539Z

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Ralph Shillington
  • 20,718
  • 23
  • 91
  • 154