Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose query between Start Date and End Date of a given collection

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.

like image 668
TBE Avatar asked Feb 01 '16 09:02

TBE


1 Answers

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

like image 130
Ralph Shillington Avatar answered Nov 10 '22 08:11

Ralph Shillington