Answer the question
In order to leave comments, you need to log in
How to count number of results with specific value in mongo (aggregation)?
I am developing a rating system for the game mafia.
Objects in the mongo database look like this:
{
"_id": "606e62f039d51433548ed934",
"date": "2021-04-08T01:55:03.759Z",
"bmove": [1,4,9],
"result": "mafia",
"fkill": 5,
"players": [
{
"slot": 1,
"nickname": {
"id":"605ca4d15bf2d053f08041e1",
"name":"player1"},
"role": "mafia",
"point": 1,
"extra": 0.3,
"fouls": 3
},
{
"slot": 2,
"nickname": {
"id":"605ca4d15bf2d053f08041e2",
"name":"player2"},
"role": "civilian",
"point": 0,
"extra": 0,
"fouls": 2
},
...
]
}
const allRatings = await Game.aggregate([
{$unwind: "$players"},
{$unwind: "$players.nickname"},
{$group: {
_id: "$players.nickname.name",
allgames: {$sum:1 },
totalpoints: { $sum: "$players.point" },
totalextra: { $sum: "$players.extra" },
totalfouls: { $sum: "$players.fouls" },
total: { $sum: { $sum: ["$players.extra", "$players.point"] } },
}},
{$sort: {total:-1}},
])
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question