I have collection like below named as "FormData",
{
"_id": ObjectId("5e3c27bf1ef77236945ef07b"),
"eed12747-0923-4290-b09c-5a05107f5609": "20200206",
"bd637691-782d-4cfd-8624-feeedfe11b3e": "[email protected]"
}
I have another collection named as "Form" which will have Title of Fields,
{
"_id": ObjectId("5e3c27bf1ef77236945ef07b"),
"Fields":[
{
"FieldID": "eed12747-0923-4290-b09c-5a05107f5609",
"Title": "Phone"
},
{
"FieldID": "bd637691-782d-4cfd-8624-feeedfe11b3e",
"Title": "Email"
}]
}
Now I have to map element name with Form field title and I need result like below,
{
"_id": ObjectId("5e3c27bf1ef77236945ef07b"),
"Phone": "20200206",
"Email": "[email protected]"
}
Please help me to solve this.
Thanks in advance!
2
Answers
You can:
$objectToArray
to convert the$$ROOT
document into an array of k-v pairs for future lookups$lookup
to find the value by the uuid$mergeObject
to combine the original values(i.e. "20200206"…) with the new field name looked up (i.e. "Phone"…)$arrayToObject
and$replaceRoot
Mongo Playground
Another option is to start from
Form
collection and avoid$unwind
:$match
and$lookup
to get all needed data into one document$objectToArray
to get known keys forFormData
$indexOfArray
and$arrayElemAt
and merge them using$mergeObjects
. Then usearrayToObject
to format the responseSee how it works on the playground example