Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda