Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
Group by count for boolean values in collection

If I have the follow data:

[{
  flagOne: true,
  flagTwo: true
},
{
  flagOne: true,
  flagTwo: false
},
{
  flagOne: true,
  flagTwo: false
},
{
  flagOne: true,
  flagTwo: true,
  flagThree: true
}]

Note that the flag may not be set and should be treated as false.

How do I get something like this aggregation result?

{
  flagOne: 4,
  flagTwo: 2,
  flagThree: 1
}

Basically, I would like to know the # of documents in my collection grouped by each of the boolean flags.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

It doesn't matter whether flagThree exists, or it's equal to "tomato". Just count flags only if they have value true:

db.getCollection('so').aggregate([
    {
        $group: { 
            _id : 1,
            flagOne: {$sum: {$cond: [{$eq:["$flagOne", true]}, 1, 0]}},
            flagTwo: {$sum: {$cond: [{$eq:["$flagTwo", true]}, 1, 0]}},
            flagThree: {$sum: {$cond: [{$eq:["$flagThree", true]}, 1, 0]}},
        }
    },
    {$project: {_id:0}}
])

Output:

{
    "flagOne" : 4,
    "flagTwo" : 2,
    "flagThree" : 1
}

If you are completely sure all flags can have only boolean values, you can simplify query to

db.getCollection('so').aggregate([
    {
        $group: { 
            _id : 1,
            flagOne: {$sum: {$cond: ["$flagOne", 1, 0]}},
            flagTwo: {$sum: {$cond: ["$flagTwo", 1, 0]}},
            flagThree: {$sum: {$cond: ["$flagThree", 1, 0]}},
        }
    },
    {$project: {_id:0}}
])
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda