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.
CodePudding user response:
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" } }
]