Reputation: 65
I have this document in my database:
[
{
"_id": {
"$oid": "5f5f280ffa2236115655cb6a"
},
"Name": "Rovilio Chipman",
"Last_season": {
"year": "2010-2011",
"goals": 10,
"assists": 1
},
"Last_season_2": {
"year": "2011-2012",
"goals": 1,
"assists": 12
},
"Seasons": [
{
"year": "2012-2013",
"goals": 11,
"assists": 4
},
{
"year": "2013-2014",
"goals": 6,
"assists": 2
},
{
"year": "2014-2015",
"goals": 5,
"assists": 5
}
]
}
]
I would like to get the average of all goals, ie the average of the goals included in "Last_season", "Last_season_2" and "Season". The result should be 33/5 = 6.6.
NB: the documents on which to make this average are of different size, ie the "Season" array can contain a different number of documents and not fixed.
How do I calculate this average in this case? How do I code it with Java Driver?
Upvotes: 0
Views: 130
Reputation: 678
Please check if this works for you:
[
{
$set: {
"Seasons": {
$concatArrays: [
"$Seasons",
[
"$Last_season_2",
"$Last_season"
]
]
}
}
},
{
$project: {
"Name": 1,
"avgGoals": {
$divide: [
{
$reduce: {
input: "$Seasons",
initialValue: 0,
in: {
$sum: [
"$$this.goals",
"$$value"
]
}
}
},
{
$size: "$Seasons"
}
]
}
}
}
]
Upvotes: 1
Reputation: 2474
You can do that with a mongo aggregate.
db.collection.aggregate([
{
"$project": {
/* Summing goals in the Seasons list */
"seasons_goals": {
"$sum": [
"$Seasons.goals"
]
},
/* Counting the number of seasons: length of Seasons + 2 */
"nb_seasons": {
"$sum": [
{
"$size": "$Seasons"
},
2
]
},
/* Summing goals of the two last seasons */
"total": {
"$sum": [
"$Last_season.goals",
"$Last_season_2.goals"
]
}
}
},
/* Calculate the average by dividing seasons_goals+total by nb_seasons */
{
"$project": {
"result": {
"$divide": [
{
"$sum": [
"$seasons_goals",
"$total"
]
},
"$nb_seasons"
]
}
}
}
])
And here is a post on: MongoDB aggregation with Java driver
Upvotes: 1
Reputation: 59446
First you need to put all values in one array, then you can calculate the average. This could be one solution:
db.collection.aggregate([
{
$set: {
AllSeasons: {
$concatArrays: [
"$Seasons",
[ "$Last_season" ],
[ "$Last_season_2" ]
]
}
}
},
{ $set: { average: { $avg: [ "$AllSeasons.goals" ] } } },
{ $unset: "AllSeasons" }
])
Upvotes: 3