I have this in
[
{
"date": "2022-12-03T12:16:52.403Z",
"configs": [
{
"name": "Shubham",
"values": [
{
"text": "172cm",
"type": "Height",
},
{
"text": "80kg",
"type": "Weight",
},
{
"text": "male",
"type": "Gender",
},
],
}
]
},
{....},{....}
]
Want to convert config
into objects like this
[
{
"date": "2022-12-03T12:16:52.403Z",
"configs": {
"name": "Shubham",
"Height": "172cm",
"Weight": "80kg",
"Gender": "male",
}
},
{...},{...},
]
I know how to do in Javascript array map method but need to understand how to do in mongoDb query ($project).
2
Answers
Did you try this?
Here is a possible approach
$unwind
theconfigs
since it contains only 1 element$project
stage use$arrayToObject
to convert the[{k:'key1',v:'value1'},{k:'key2',v:'value2'}]
to{key1:'value1',key2:'value2'}
.$map
stage is used to convert the field names invalues
array to the above format.$concatArrays
is used to concat thename
field and value before converting array to object so that it becomes[{k:'name',v:'Shubham'},{k:'Height',v:'172cm'}...]
Playground Link