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).
CodePudding user response:
Did you try this?
arr=[];
yourOutPutJson.forEach(function(b){var obj={};obj.name=b.configs[0].name;b.configs[0].values.forEach(function(c){obj[c.type]=c.text});arr.push(obj)});
CodePudding user response:
Here is a possible approach
- First
$unwind
theconfigs
since it contains only 1 element - In the
$project
stage use$arrayToObject
to convert the[{k:'key1',v:'value1'},{k:'key2',v:'value2'}]
to{key1:'value1',key2:'value2'}
. - The
$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'}...]
db.collection.aggregate([
{
$unwind: "$configs"
},
{
$project: {
date: 1,
configs: {
$arrayToObject: {
$concatArrays: [
{
$map: {
input: "$configs.values",
as: "el",
in: {
k: "$$el.type",
v: "$$el.text"
}
}
},
[
{
k: "name",
v: "$configs.name"
}
]
]
},
},
},
},
])