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

124
Visualizações
MongDB Aggregate two values with same name

i have the following aggregate function in my code to count how many times a value is found in the db:

  let data: any = await this.dataModel.aggregate(
      [
        {
          $match: {
            field: new ObjectID(fieldID),
          },
        },
        {
          $group: {
            _id: "$value",
            total_for_value: { $sum: 1 },
          },
        },
      ]
    );

This works correctly, however my data setup is a bit different. I have two types of value fields. Some like this:

    {
    "_id" : ObjectId("123"),
    "value" : "MALE"
    }

and some like this:

{
    "_id" : ObjectId("456"),
    "value" : {
        "value" : "MALE",
    }
}

Is there a way to group the ones where the _id and the _id.value are the same? At the moment it counts them separately.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

db.collection.aggregate([
  {
    "$addFields": {
      "key2": {
        "$cond": {
          "if": {
            $and: [
              {
                "$eq": [
                  {
                    "$type": "$key"
                  },
                  "object"
                ]
              }
            ]
          },
          "then": "$key.value",
          "else": "$key"
        }
      }
    }
  },
  {
    "$group": {
      "_id": "$key2",
      "data": {
        $push: "$$ROOT"
      }
    }
  }
])

This would do the job if _id.value is an object.

Playground

about 4 years ago · Juan Pablo Isaza 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