Hello : )
Storing unknown keys in documents,its not good idea i think,because we will have to find
those keys to sum them.
With arrays we don’t find them,and mongo offers so many array operations.
Why not store an array,if all seasons exist 1,2,3 … you dont even need the field season.
The index will be the key.
If there isn’t any important reason to save the seasons inside a document,you can use
this code,i used arrays.If you need documents for some reason it can work also,but more
complicated and slow i think.
Data inserts (3 documents,last one dont have a season,works also if seasons is empty array)
[
{
"afield": "",
"seasons": [
{
"season": 1,
"wins": 10
},
{
"season": 2,
"wins": 2
}
]
},
{
"afield": "",
"seasons": [
{
"season": 1,
"wins": 4
},
{
"season": 2,
"wins": 5
}
]
},
{
"afield": ""
}
]
Update
{
"update": "testcoll",
"updates": [
{
"q": {},
"u": [
{
"$addFields": {
"totalwins": {
"$cond": [
{
"$ne": [
{
"$type": "$seasons"
},
"missing"
]
},
{
"$reduce": {
"input": "$seasons",
"initialValue": 0,
"in": {
"$add": [
"$$value",
"$$this.wins"
]
}
}
},
0
]
}
}
}
],
"multi": true
}
]
}
Query just to see the updated and got
[
{
"afield": "",
"seasons": [
{
"season": 1,
"wins": 10
},
{
"season": 2,
"wins": 2
}
],
"totalwins": 12
},
{
"afield": "",
"seasons": [
{
"season": 1,
"wins": 4
},
{
"season": 2,
"wins": 5
}
],
"totalwins": 9
},
{
"afield": "",
"totalwins": 0
}
]
Hope it helps ,its fast ,and simple code,if not important reason for document use i think its
fine.