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

224
Vistas
Aggregation in Mongodb with dynamic projection

I'm studying MongoDB with the Nodejs driver in Typescript; I would like to retrieve sub-documents from documents with a "dymanic" projection; this should be done with an array that lists the desired fields:

{ 
    "_id" : ObjectId("6006be017fdd3b1018e0f533"), 
    "name" : "Cindy", 
    "surname" : "Red", 
    "age" : 30.0, 
    "various" : {
        "aaa1" : "111", 
        "bbb2" : "222"
    }
}
{ 
    "_id" : ObjectId("6006be0b7fdd3b1018e0f534"), 
    "name" : "Valentina", 
    "surname" : "Green", 
    "age" : 30.0, 
    "various" : {
        "ccc3" : "333", 
        "ddd4" : "444"
    }
}

// This piece of code to execute the query:
const arrayValues = ["$various"];
    const result = await myConnectedClient
      .db("ZZZ_TEST_ALL")
      .collection("my_collection_01")
      .aggregate<any>([
        { $project: {  _id: 0, arrayValues } },
      ]);

Result:

{
  _id: 6006be017fdd3b1018e0f533,
  arrayValues: [ { aaa1: '111', bbb2: '222' } ]
}
{
  _id: 6006be0b7fdd3b1018e0f534,
  arrayValues: [ { ccc3: '333', ddd4: '444' } ]
}

but I would like this result:

{
  various: { aaa1: '111', bbb2: '222' }
}
{
  various:  { ccc3: '333', ddd4: '444' } 
}

Thanks.

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

0

This should do it

const arrayValues = ["$various"];
const result = await myConnectedClient
  .db("ZZZ_TEST_ALL")
  .collection("my_collection_01")
  .aggregate<any>([{ $project: { _id: 0, arrayValues } }])
  .map((e) =>
    Object.keys(e.arrayValues[0]).map((k) => {
      return { [k]: e.arrayValues[0][k] };
    })
  )
  .map((v) => {
    return { various: Object.assign({}, ...v) };
  });

Prints (as JSON)

[
  { "various": { "aaa1": "111", "bbb2": "222" } },
  { "various": { "ccc3": "333", "ddd4": "444" } }
]
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