I am having a MongoDB aggregate result:
{
"healthDetails": [
{
"problem": "Fever",
"note": "normal"
},
{
"problem": "Allergy",
"note": "critical"
}
]
}
I need to convert the above array like this:
{
"healthDetails": "Fever - normal, Allergy - critical"
}
Need to remove square brackets and double quotes and concat the values by comma-separated.
How to do that in MongoDB projection?
Need some valuable help.
>Solution :
Work with aggregation pipeline.
-
$reduce– Iterate the elements in thehealthDetailsarray and transform into the string by concatenating the value with$concat. -
$trim– Remove the beginning and ending characters for ", " from the result generated in 1.
db.collection.aggregate([
{
$set: {
"healthDetails": {
$trim: {
input: {
$reduce: {
input: "$healthDetails",
initialValue: "",
in: {
$concat: [
"$$value",
", ",
{
$concat: [
"$$this.problem",
" - ",
"$$this.note"
]
}
]
}
}
},
chars: ", "
}
}
}
}
])