Database

db={"Location":[{"_id":1,"name":"FORA","type":"REST"},{"_id":2,"name":"Sala 1","type":"ROOM"},{"_id":3,"name":"Sala 2","type":"ROOM"},{"_id":4,"name":"Patio","type":"COURTYARD"}],"Sensor":[{"_id":1,"name":"Sensor interno 1","placementType":"INTERNAL","location":1},{"_id":2,"name":"Sensor interno 2","placementType":"INTERNAL","location":2},{"_id":3,"name":"Sensor interno 1","placementType":"EXTERNAL","location":3}],"Worker":[{"_id":1,"name":"Fulano"},{"_id":2,"name":"Ciclano"},{"_id":3,"name":"Beltrano"}],"WorkerLocationContext":[{"_id":1,"worker":1,"location":1,"createdAt":1},{"_id":2,"worker":2,"location":1,"createdAt":2},{"_id":3,"worker":2,"location":3,"createdAt":3},{"_id":4,"worker":3,"location":3,"createdAt":3},{"_id":5,"worker":2,"location":4,"createdAt":4},],"HeatMeasureContext":[{"_id":1,"location":2,"internal":27,"createdAt":1},{"_id":2,"location":3,"internal":29,"createdAt":1},{"_id":3,"location":4,"external":25,"createdAt":1},{"_id":4,"location":2,"internal":26,"createdAt":2},{"_id":5,"location":3,"internal":29,"createdAt":2},{"_id":6,"location":4,"internal":26,"createdAt":2},{"_id":7,"location":2,"internal":28,"createdAt":3},{"_id":8,"location":3,"internal":29,"createdAt":3},{"_id":9,"location":4,"internal":25,"createdAt":3},{"_id":10,"location":2,"internal":27,"createdAt":4},{"_id":11,"location":3,"internal":30,"createdAt":4},{"_id":12,"location":4,"internal":26,"createdAt":4},{"_id":13,"location":4,"internal":31,"createdAt":4}]}

Query

db.HeatMeasureContext.aggregate([{$match:{$expr:{$or:[{$gte:["$internal",27]},{$gte:["$external",27]}]}}},{"$lookup":{"from":"WorkerLocationContext",let:{loc:"$location"},pipeline:[{$match:{$expr:{$eq:["$$loc","$location"]}}},{$group:{_id:"$location","workers":{"$sum":1},"wlDatetime":{"$max":"$createdAt"}}}],"as":"workerAggResult"}},{$unwind:"$workerAggResult"},{$group:{_id:"$location","hmDatetime":{$max:"$createdAt"},"wlDatetime":{$first:"$workerAggResult.wlDatetime"},"workers":{$first:"$workerAggResult.workers"}}}])

Result