I am trying to manipulate a dataset to make it easy to display in mongoCharts. There are two sets of scores firstscores and last scores, Each contains a set of score names and score values. I want to be able to calculate the difference between first and last values for each of A, ,B and C.
Example input…
{
"firstscores" : [
{
"content" : {
"scores" : [
{
"score_name" : "A",
"score_value" : 1
},
{
"score_name" : "B",
"score_value" : 2
},
{
"score_name" : "C",
"score_value" : 3
}
]
}
}
],
"lastestscores" : [
{
"content" : {
"scores" : [
{
"score_name" : "A",
"score_value" : 9
},
{
"score_name" : "B",
"score_value" : 8
},
{
"score_name" : "C",
"score_value" : 7
}
]
}
}
]
}
Desired Output
"allscores" : [{
"content" : {
"scores" : [
{
"score_name" : "A",
"first_score_value" : 1,
"last_score_value" : 9
"diff": 8
},
{
"score_name" : "B",
"first_score_value" : 2,
"last_score_value" : 8
"diff": 6
},
{
"score_name" : "C",
"first_score_value" : 3,
"last_score_value" : 7
"diff": 4
}
]
}
}]
Note
"first_score_value" : 1,
"last_score_value" : 9
are optional/nice to haves. Its the diff that I’m really after.
So far I've tried adding the latest score to the first score array ,
{$addFields: {
'firstscores.content.scores.lastscore_name.0': { $arrayElemAt: ['$lastscores.content.scores.score_name',0]}
}}
gives all the latestscore values
0:Object
score_name:"A"
score_value:1
lastscore_name:Object
0:"A"
1:"B"
2:"C"
Also tried a combination of zips
{$addFields: {
both: {$zip:{inputs: ['$firstscores.content.scores','$firstscores.content.scores.score_value','$lastscores.content.scores.score_value']}}
}}
, {$addFields: {
botha: {$arrayElemAt: ['$both',0]},
}},
{$addFields: {
firstandlastscores: {$zip:{inputs: [{ $arrayElemAt: ['$botha',0]},{ $arrayElemAt: ['$botha',1]},{ $arrayElemAt: ['$botha',2]}]}}
}}]
but lost the attribute names,
firstandlastscores:Array
0:Array
0:Object
score_name:"A"
score_value:1
1:1
2:9
1:Array
0:Object
score_name:"B"
score_value_string:2
1:2
2:8
2:Array
0:Object
score_name:"C"
score_value_string:3
1:3
2:7
mergeObjects overwrote the fields of the same name .
I think map reduce may be the way to go but I have not managed to get any where near with that option.
Any guidance or pointers gratefully received.