Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
Agregación en Mongodb con proyección dinámica

Estoy estudiando MongoDB con el controlador Nodejs en Typescript; Me gustaría recuperar subdocumentos de documentos con una proyección "dinámica"; esto debe hacerse con una matriz que enumere los campos deseados:

 { "_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 } }, ]);

Resultado:

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

pero me gustaría este resultado:

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

Gracias.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

esto debería hacerlo

 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) }; });

Imprime (como JSON)

 [ { "various": { "aaa1": "111", "bbb2": "222" } }, { "various": { "ccc3": "333", "ddd4": "444" } } ]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!