Database
[{user_id:"1",sessions:[{actions:[{type:"create",created_at:ISODate("2020-01-01"),},{type:"read",created_at:ISODate("2022-01-01"),},{type:"read",created_at:ISODate("2021-01-01"),}],}]}]
Query
db.collection.aggregate([{$unwind:"$sessions"},{$unwind:"$sessions.actions"},{$group:{_id:{user_id:"$user_id",type:"$sessions.actions.type"},last:{$max:"$sessions.actions.created_at"},count:{$sum:1},}},{$group:{_id:{user_id:"$_id.user_id"},actions:{$push:{type:"$_id.type",last:"$last",count:"$count"}}}},{$project:{_id:0,user_id:"$_id.user_id",actions:{"$function":{"body":"function(doc) { const ops = {read:0, delete:0, update: 0, create: 0}; const actions = doc.actions; actions.forEach(action => { ops[action.type] = 1 }); Object.keys(ops).filter(key => ops[key] === 0).forEach(key => actions.push({count: 0, last: null, type: key})); return actions }","args":["$$ROOT"],"lang":"js"}},}},])