I
I
Igor2021-09-10 04:27:23
Mongoose
Igor, 2021-09-10 04:27:23

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     
    },

    ...
  ]
}


The data aggregation looks like this:
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}},
    ])


I output and convert all numerical values ​​​​as I need.
Requires values ​​for when a player played a specific role and number of wins for a specific role.

The question is: how to calculate the total number of results for a single player
when "role": "mafia" and when "role": "mafia" at "point": 1

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question