I have the following document structure:
{
"_id" : ObjectId("5a16b7cf930a1e000465d1c5"),
"trackerId" : ObjectId("5a16b7b8930a1e000465d1c1"),
"trackingEvents" : [
{
"type" : "checkin",
"timestamp" : ISODate("2017-11-23T11:57:43.710Z"),
},
{
"type" : "connectivity",
"timestamp" : ISODate("2017-11-23T11:57:47.011Z"),
},
{
"type" : "power",
"timestamp" : ISODate("2017-11-23T11:57:47.036Z"),
}
]
}
I would like to setup a query to count number of trackingEvents with "type":"power" grouped by day for all trackingEvents happened < 1 month ago. And have the following query which works fine, except for the fact that it is not fast enough:
db.getCollection('trackerEvents').aggregate( [
{$unwind: "$trackingEvents"},
{$match:
{
"trackingEvents.type": "power",
"trackingEvents.timestamp": {
"$gt": {
"$humanTime": "1 month ago" //redash operator
}
}
}
},
{
"$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": "$trackingEvents.timestamp"
}
},
count: {$sum: 1}
}
},
,
{ $sort : { "_id":1 } }
])
However, this query did not pass the code review as my colleague suggested to swap $match and $unwind operators so that $match goes before $unwind in order to increase perfomance of the query. If I swap these two operators, I get different results, could someone please suggest how is it possible to $match array elements of the document before $unwind?
Thanks!
$filteroperator for arrays. You could already filter the results out before you unwind