1
{
    "_id": {
        "$__id": "608028497a90cf06c02b1083"
    },
    "name": "Player Unknown's Batteground Mobile",
    "publisher_detail": "Bluehole Corporation",
    "release_date": {
        "$date": "2017-03-26T18:30:00.000Z"
    },
    "version": "1.2.0",
    "genre": "action",
    "rating": 100,
    "achievement": [{
        "name": "Ace",
        "players": [{
            "player_name": "notAplayer",
            "score": 60,
            "date_of_achievement": {
                "$date": "2019-02-14T18:30:00.000Z"
            },
            {
            "player_name": "notAplayer2",
            "score": 92,
            "date_of_achievement": {
                "$date": "2020-04-14T18:30:00.000Z"
            }
        }]
    }]
}

I have the following mongodb schema for a gaming system.I want to write a query to find maximum score in each game. Not able to figure out what to do!

2 Answers 2

2
  • $map to iterate loop of achievement.players.score and get max from array of array
  • $max to get maximum number from array
db.collection.aggregate([
  {
    $addFields: {
      maxScore: {
        $max: {
          $map: {
            input: "$achievement.players.score",
            in: { $max: "$$this" }
          }
        }
      }
    }
  }
])

Playground

Sign up to request clarification or add additional context in comments.

Comments

0

Not fully clear what you mean by max score in each game (what is a "game") but a simple solution is this:

db.collection.aggregate([
  {
    $addFields: {
      max_score: {
        $max: {
          $max: "$achievement.players.score"
        }
      }
    }
  }
])

4 Comments

Each document represent one game. For instance the above example represents PUBG game, i want to show top scorer from each game. For the above example the top scorer is notAplayer2
"find maximum score in each game" is different to "show top scorer from each game". Please review your question.
Hi @WernfriedDomscheit nested $max will fail in this situation see playground if i am not wrong.
Yes, you are right. However, the question is not clear anyway, see above comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.