sql >> Base de Datos >  >> NoSQL >> MongoDB

¿Cómo calcular el porcentaje usando faceta en MongoDB?

Puedes probar,

  • $group por userId y obtenga totalSeen cuenta usando $cond si status es seen , 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]
      }
    }
  }
])

Patio de juegos