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

Cuente una propiedad de subdocumento en una proyección usando MongoDB y Javascript

  • $map para iterar el bucle de subRoom matriz y in para devolver los campos obligatorios
  • $filter para iterar el bucle de notifications y $size para obtener el total de elementos del resultado filtrado
db.collection.find({ id: 1 },
{
  _id: 0,
  room: 1,
  notRead: {
    $size: {
      $filter: {
        input: "$notifications",
        cond: {
          $not: { $in: ["User1", "$$this.read"] }
        }
      }
    }
  },
  "subRoom": {
    $map: {
      input: "$subRoom",
      in: {
        id: "$$this.id",
        notRead: {
          $size: {
            $filter: {
              input: "$$this.notifications",
              cond: { $not: { $in: ["User1", "$$this.read"] } }
            }
          }
        }
      }
    }
  }
})

Patio de juegos