Puedes probar,
$group
poruserId
y obtengatotalSeen
cuenta usando$cond
sistatus
esseen
, obtenga el recuento total de notificaciones usando$sum
,$project
para mostrar los campos obligatorios y calcular el porcentaje usando$divide
y$multiply
db.collection.aggregate([
{
$group: {
_id: "$userId",
totalSeen: {
$sum: { $cond: [{ $eq: ["$status", "seen"] }, 1, 0] }
},
total: { $sum: 1 }
}
},
{
$project: {
_id: 0,
userId: "$_id",
notificationPercentage: {
$multiply: [{ $divide: ["$totalSeen", "$total"] }, 100]
}
}
}
])