How to find records in MongoDB based on start and end date considering days

Viewed 39

How to return multiple objects from MongoDB using start, end date considering the days?

User Input -

start = "2022-09-08"
end   = "2022-09-17" 

MongoDB Object

{
        "id": "63199ee82baa3643e58ed0f1",
        "start": "2022-09-08",
        "end": "2022-09-20",
        "startTime": "09:00",
        "endTime": "05:10",
        "timezone": "Europe/Rome",
        "days": [
            "Friday"
        ],
        "type": {
            "type": "remote",
            "label": "Video"
        },
        "interval": "15m",
        "store": "63199ee82baa3643e5887676"
    }

Expected Output - returning 2022-09-09 and 2022-09-16 as both lies in between start and end date also it's friday

    [{
        "id": "63199ee82baa3643e58ed0f1",
        "start": "2022-09-09",
        "end": "2022-09-09",
        "startTime": "09:00",
        "endTime": "05:10",
        "timezone": "Europe/Rome",
        "days": [
            "Friday"
        ],
        "type": {
            "type": "remote",
            "label": "Video"
        },
        "interval": "15m",
        "store": "63199ee82baa3643e5887676"
    },
    {
        "id": "63199ee82baa3643e58ed0f1",
        "start": "2022-09-16",
        "end": "2022-09-16",
        "startTime": "09:00",
        "endTime": "05:10",
        "timezone": "Europe/Rome",
        "days": [
            "Friday"
        ],
        "type": {
            "type": "remote",
            "label": "Video"
        },
        "interval": "15m",
        "store": "63199ee82baa3643e5887676"
    }]
1 Answers

I think you should use mongodb aggregations, you should use $match aggregation to see the results between the start and end dates with specific day as follow:

[{
    $match: {
        start: {
            $gt: '2022-09-08'
        },
        end: {
            $lt: '2022-09-17'
        },
        days: {
            $exists: 'Friday'
        }
    }
}]

By the way you can use mongo compass to use aggregations, if you'd like to have a gui environment

Related