This is my first question ever here so super excited to learn and apologies if the syntax is not up to mark, I will improve with time.
"item"
is an Array ( this doc has only one element)"adjudication"
is a nested Array with a variable number of elements(same structure)- I want to create keys out of
"adjudication.category.coding.code"
without hardcoding as the values will be different with each document but will have the same string length - I tried using
"$map"
to apply the same logic to each array element but failed
"item": [
{
"adjudication": [
{
"amount": {"code": "USD", "system": "4217", "value": 22.51},
"category": {
"coding": [
{
"code": "bb.org/paid_amt",
"system": "bb.org/adjudication"
}
]
},
"reason": {
"coding": [
{
"code": "C",
"system": "bb.org/cvrg_status"
}
]
}
},
{
"amount": {"code": "USD", "system": "4217", "value": 0},
"category": {
"coding": [
{
"code": "bb.org/discount_amt",
"system": "bb.org/adjudication"
}
]
}
}
]
}
]
Output desired
adjudication: {paid_amt: 22.51, discount_amt: 0}
2
Answers
Welcome to SO. I hope the following code will solve your exception. Sometime you may modify based on you wish.
$unwind
to deconstruct the array$map
to loop / modify through the array, and$arrayElementAt
to. get the first object from the array$let
to find the last potion by$split
ing for "paid_amt" and "discount_amt". So this will be an array of object. But you need objects. So the next part I make it as k:v pair.$arrayToObject
to make array to object by using above k:v pair. ("k" and "v" names are must. Can’t replace by any other names)$group
to reconstruct the array that we did in 1st stepHere is the code,
Working Mongo playground
try this playground