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

123
Vistas
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 Respuestas
Responde la pregunta

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 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