MongoDB, Data between two Dates, records that match StartTime Irrespective of EndTime, records that match EndTime Irrespective of StartTime

Viewed 37

For Example:

[
    {
        "title": "test1",
        "startDate": "2022-05-16T10:56:33.005Z",
        "endDate": "2022-05-16T13:56:33.005Z",
    },
    {
        "title": "test2",
        "startDate": "2022-05-11T00:00:00.000Z",
        "endDate": "2022-05-11T00:00:00.000Z",
    },
    {
        "title": "test3",
        "startDate": "2022-05-19T00:00:00.000Z",
        "endDate": "2022-05-19T00:00:00.000Z",
    },
    {
        "title": "test4",
        "startDate": "2022-05-16T12:00:33.005Z",
        "endDate": "2022-05-16T13:56:33.005Z",
    },
    {
        "title": "test5",
        "startDate": "2022-05-16T11:00:33.005Z",
        "endDate": "2022-05-16T15:56:33.005Z",
    },
    {
        "title": "test6",
        "startDate": "2022-05-16T14:50:33.005Z",
        "endDate": "2022-05-17T01:50:33.005Z",
    }
]

,

1 Answers

As a result of my research, I found the answer

query = {
$or: [
    { // inbetween
    $and: [
            { startDate: { $gte: new Date(data.from_date)
                }
            },
            { endDate: { $lte: new Date(data.to_date)
                }
            },
        ]
    },
    { // 3 to 5 ----- 1 to 4 hours

    $and: [
            { startDate: { $lte: new Date(data.from_date)
                }
            },
            { endDate: { $gte: new Date(data.from_date)
                }
            },
        ]
    },
    { // 3 to 5 ---- 4 to 8 hours
    $and: [
            { startDate: { $lte: new Date(data.to_date)
                }
            },
            { endDate: { $gte: new Date(data.to_date)
                }
            },
        ]
    }
]

}

Answer: [ { "title": "test1", "startDate": "2022-05-16T10:56:33.005Z", "endDate": "2022-05-16T13:56:33.005Z", }, { "title": "test4", "startDate": "2022-05-16T12:00:33.005Z", "endDate": "2022-05-16T13:56:33.005Z", }, { "title": "test5", "startDate": "2022-05-16T11:00:33.005Z", "endDate": "2022-05-16T15:56:33.005Z", }, { "title": "test6", "startDate": "2022-05-16T14:50:33.005Z", "endDate": "2022-05-17T01:50:33.005Z", } ],

Related