I am doing a little hobby project for friends' disc golf results.
I'm fairly new to MongoDB and I've stuck on a query. What I want to do is to return a JSON object on the form [{player: "Name", totalThrows: (sum of Totalt field), total+/-: (sum of +/- field)}].
So in short: I want to aggregate each players total throws (Total field) and total+/-, over 3 different documents in my database.
The final JSON would look like this: [{player: "Tormod", totalThrows: 148, total+/-: 24}, {player: "Martin", totalThrows: 149, total+/-: 25}, {player: "Andreas", totalThrows: 158, total+/-: 34}]
The picture below shows my document as it's saved in MongoDB. The results array consist of the results of a specific player discgolf results. There is also not a set order on which player is first in the results array in the different documents. Each document represents a new round (think of playing 3 different days).
Code:
aggregate(
[
{$unwind: "$results"},
{$group: {
player: "$results.PlayerName",
throws: "$results.Totalt"
}},
{$group: {
_id: "$_id",
totalThrows: {$sum: "$results.Totalt"}
}}
])
