Seeking a way to extract specific values and calculate the frequency of those values in a collection based on a certain key's ID. Consider this example of a single document from a Game Logs collection:
{
"_id": "5af88940b73b2936dcb6dfdb",
"date": "2018-05-13T18:51:44.548Z",
"playerOne": "5af888d0b73b2936dcb6dfd3",
"playerOneThrew": "Scissors",
"playerTwo": "5af88918b73b2936dcb6dfd7",
"playerTwoThrew": "Rock",
"winner": "5af88918b73b2936dcb6dfd7",
"__v": 0
}
The goal is to query based on a Player's ID (either playerOne or playerTwo) and retrieve the hand that player threw for each game. The objective is to obtain a total count of all hands thrown (rock, paper, scissors) by a specific Player's ID.
Is there a method to aggregate a count for each "thrown hand" value across all documents in a collection and generate an output like:
{
"player": "5af888d0b73b2936dcb6dfd3",
"Rock": 3,
"Paper": 6,
"Scissors": 12
}
I've been contemplating setting a variable based on matching playerOne || playerTwo IDs, then employing a switch statement to aggregate counts of "rock", "paper", "scissors". However, my limited experience with MongoDB syntax has made it challenging to execute such a query effectively.
Below is my current approach:
GameLogs.aggregate(
[
{
$let: {
vars: {
playerThrew: {
$cond: {
if: {
$eq: { playerOne: id },
}
}, then: playerOneThrew, else: playerTwoThrew
}
}
}
},
{
$switch: {
branches: [
{ case: { $eq: 'Rock' }, then: { $count: 'Rock' } },
{ case: { $eq: 'Paper' }, then: { $count: 'Paper' } },
{ case: { $eq: 'Scissors' }, then: { $count: 'Scissors' } },
]
}
}
]
)
Pseudocode:
if playerOne == id
playerThrew = playerOneThrows
else if playerTwo == id
playerThrew = playerTwoThrows
switch playerThrew {
case 'rock':
rockCount++
break
case 'paper':
paperCount++
break
case 'scissors':
scissorsCount++
break
}
return {
player_id: id,
rock: rockCount,
paper: paperCount,
scissors: scissorCount
}
Any guidance on this matter would be greatly appreciated.