I have one nested object in Compass MongoDB:
{
"data_rm": {
"pembiayaan": {
"name": "pembiayaan",
"value": "asuransi",
"type": "radio",
"title": ""
},
"asuransi": {
"name": "asuransi",
"value": "ADMEDIKA - FWD LIFE INDONESIA (FINANSIAL WIRAMITRA DANADYAKSA, PT)",
"type": "select-one",
"text": "ADMEDIKA - FWD LIFE INDONESIA (FINANSIAL WIRAMITRA DANADYAKSA, PT)",
"title": ""
},
"informasi_diperoleh_dari": {
"name": "informasi_diperoleh_dari",
"value": "pasien",
"type": "radio",
"title": ""
},
"cara_datang": {
"name": "cara_datang",
"value": "sendiri",
"type": "radio",
"title": ""
},
"nama_pengantar": {
"name": "nama_pengantar",
"value": "Tn. BAGUS",
"type": "text",
"title": ""
},
"no_telp_pengantar": {
"name": "no_telp_pengantar",
"value": "0813xxxxxxxx",
"type": "text",
"title": ""
}
}
How did I return the document WHERE type is "select-one"? (I want to find which key in data_rm has the type of select-one)
** EDIT **
The desired output is:
{
data_rm: {
"asuransi": {
"name": "asuransi",
"value": "ADMEDIKA - FWD LIFE INDONESIA (FINANSIAL WIRAMITRA DANADYAKSA, PT)",
"type": "select-one",
"text": "ADMEDIKA - FWD LIFE INDONESIA (FINANSIAL WIRAMITRA DANADYAKSA, PT)",
"title": ""
}
}
}
CodePudding user response:
Here's one way you could do it. In Compass you can enter each stage of the aggregation pipeline.
db.collection.aggregate([
{
"$set": { "rmArray": { "$objectToArray": "$data_rm" } }
},
{
"$set": {
"selOne": {
"$filter": {
"input": "$rmArray",
"cond": { "$eq": [ "$$this.v.type", "select-one" ] }
}
}
}
},
{
"$replaceWith": { "data_rm": {"$arrayToObject": "$selOne" } }
}
])
Try it on mongoplayground.net.