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.
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" } } ]