MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Como calcular a porcentagem usando faceta no MongoDB?


Podes tentar,
  • $group por userId e obtenha totalSeen contar usando $cond se status é seen , obtenha a contagem total de notificações usando $sum ,
  • $project para mostrar os campos obrigatórios e calcular a porcentagem usando $divide e $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]
      }
    }
  }
])

Playground