Mongo: Using $dayOfWeek in a $match clause when query has also a $groupy Mongo: Using $dayOfWeek in a $match clause when query has also a $groupy mongodb mongodb

Mongo: Using $dayOfWeek in a $match clause when query has also a $groupy


You should use $dayOfWeek inside $project like so:

[{<your match by date>}, {$project:{vehicleId:1, telemetryDate:1, alarmsTotal:1, dow:{$dayOfWeek:'$telemetryDate'}}}, {$match:{dow:{$in:[2,3,4,5,6]}}}, <rest of pipeline> ]

btw, your first $match can benefit from using index, like normal find command. It will improve performance on large datasets.


It's actually pretty simple to do this - you can use $project to create new fields that didn't exist in the original document - you can compute new values or you can conditionally project different values, depending on what original values are. You can even calculate in a single group phase both total alarms as well as only alarms on weekdays.

Here is what you need to do in the project phase:

{"$project" : {        "vehicleId" : 1,        "telemetryDate" : 1,        "alarmsTotal" : 1,        "alarmsWeekdays" : {            "$cond" : [                {                    "$or" : [                        {                            "$eq" : [                                {                                    "$dayOfWeek" : "$telemetryDate"                                },                                1                            ]                        },                        {                            "$eq" : [                                {                                    "$dayOfWeek" : "$telemetryDate"                                },                                7                            ]                        }                    ]                },                0,                "$alarmsTotal"            ]        }    }}

The above says: "Pass through these three fields, but also compute a new field alarmWeekdays like so: ..."

The actual expression in more "English" terms happens to be:

IF `$dayOfWeek` of telemetryDate is equal to 1 OR `$dayOfWeek` of telemetryDate is equal to 7THEN `$project` the value 0 as `alarmsWeekdaysELSE `$project` the value from `$alarmsTotal` as `alarmsWeekdays`