I wanted to rename field inside a nested array of objects which looks like below:
{
"_id":"63ca455cb7dd228bcb3d85e5"
"name": "Alex",
"phoneNumber": "+235946546654",
"level": 5,
"workByCateg": [
{
"workId": "741qaz852wsx963edc",
"customWork": [
{
"dName": "Status",
"type": "options",
"value": "Others"
},
{
"dName": "Appointment",
"type": "dateTime",
"value": 1324645625
},
{
"dName": "Notes",
"type": "status",
"value": "hi hello how are you.."
}
]
},
{
"workId": "123qaz456wsx789edc",
"customWork": [
{
"dName": "Status",
"type": "options",
"value": "Work Done"
},
{
"dName": "Appointment",
"type": "dateTime",
"value": 1326546546
},
{
"dName": "Cus-Field",
"type": "multi-options",
"value": ["opt1", "opt2"]
}
]
}
]
}
I want to retain this structure, but do some changes like the following, on the result:
- change the field name from “dName” to “name”
- remove the field “type” from “customWork” field.
I don’t want to make changes to the database.
The following is the aggregation that I use:
[
{
$match: <my_query>
},
{
$unwind: "$workByCateg",
},
{
$set: {
workByCateg: {
processId: "$workByCateg.workId",
customWork: {
$map: {
input: "$workByCateg.customWork",
as: "theField",
in: {
name: "$$theField.dName",
value: "$$theField.value",
},
},
},
},
},
},
{
$addFields: {
"workByCateg.customWork": {
$ifNull: ["$customWork", "$$REMOVE"],
},
},
},
{
$group: {
_id: "$_id",
name: { $last: "$name" },
phoneNumber: { $last: "$phoneNumber" },
level: { $last: "$level" },
workByCateg: { $push: "$workByCateg" },
},
},
]
Here I’m doing unwind first, to change field names, and then im grouping it again to club all “customWork” together under “workByCateg” field.
I feel like the aggregation that i use is an overkill and thinking about performance issues. Any straight forward approach for this?
Any help would be appreciated. Thank you for your time.