Filter time slot array

Hi, I have this time slot array.

"schedule" : {
        "monday" : [
            {
                "_id" : ObjectId("62667b8f77b24028c80d1d3d"), 
                "startTime" : "12:00", 
                "endTime" : "2:00", 
                "price" : 100.01
            }, 
            {
                "_id" : ObjectId("62667b8f77b24028c80d1d3e"), 
                "startTime" : "19:00", 
                "endTime" : "20:00", 
                "price" : 101.01
            }
        ], 
        "tuesday" : [
            {
                "_id" : ObjectId("62667b8f77b24028c80d1d3f"), 
                "startTime" : "23:00", 
                "endTime" : "23:59"
            }
        ], 
}

I want to filter the array based on the given time slot.

For example, if I provide Monday with the time 19:00. So in that case I want a result whose start time equal to or greater than 19:00

So as per the input, I will get a result

"schedule" : {
        "monday" : [
            {
                "_id" : ObjectId("62667b8f77b24028c80d1d3e"), 
                "startTime" : "19:00", 
                "endTime" : "20:00", 
                "price" : 101.01
            }
        ], }

So the first record of the Monday array will not be shown. because it’s time is 12:00 i.e less then 19:00
So how can filter it using aggregation? can anyone please guide me?

Thanks.

Read Formatting code and log snippets in posts and republish your documents. We cannot use them, by cut-n-paste into our system because of the way they are published the quotes are wrong.

Also share what you have tried so far and how it fails to provide the correct results. This will help us avoiding to experiment in a wrong direction.

Without giving too much thought, you could use a $project stage to get the specified day.

Untested snippet

specified_day = "monday"

project_stage = { "$project" : { today : "$schedule." + specified_day } }

collection.aggregate( [ project_stage ] )

But the above will give all schedule.monday array. Using $filter allows you to only keep the appropriate elements.

To filter an array, you need https://www.mongodb.com/docs/manual/reference/operator/aggregation/filter/.

$filter : {
  "input" :  "schedule." + specified_day ,
  "as" : "filtered" ,
  "cond" : [ ]
}
1 Like