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

188
Vistas
Mongodb Aggregate with nested subdocuments

I have a document looking like this:

{
  "_id": "some_uuid",
  "inv": {
    "food01": "id01",
    "food02": "id02",
    "food03": "id03"
  },
  "food": {
    "id01": {
      "n": "apple"
    },
    "id02": {
      "n": "banana"
    },
    "id03": {
      "n": "pear"
    }
  }
}

I want to use Mongodb Aggregate to retrieve the following output.

Expected Output

{
    "_id": "some_uuid",
  "inv": {
    "food01": "apple",
    "food02": "banana",
    "food03": "pear"
  }
}

Can someone guide me how to do this? Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

One option is using $objectToArray to format these fields as arrays, which will allow to use $map and $filter to match them:

db.collection.aggregate([
  {$set: {inv: {$objectToArray: "$inv"}, food: {$objectToArray: "$food"}}},
  {
    $project: {
      inv: {$map: {
          input: "$inv",
          in: {
            k: "$$this.k",
            v: {
              $filter: {
                input: "$food",
                as: "food",
                cond: {$eq: ["$$this.v", "$$food.k"]}
              }
            }
          }
        }
      }
    }
  },
  {
    $project: {
      inv: {
        $map: {
          input: "$inv",
          in: {k: "$$this.k", v: {$first: "$$this.v.v.n"}}
        }
      }
    }
  },
  {$project: {inv: {$arrayToObject: "$inv"}}}
])

See how it works on the playground example

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