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

Conte uma propriedade de subdocumento em uma projeção usando MongoDB e Javascript

  • $map para iterar o loop de subRoom array e in para retornar os campos obrigatórios
  • $filter para iterar o loop de notifications e $size para obter o total de elementos do 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"] } }
            }
          }
        }
      }
    }
  }
})

Playground