简体   繁体   中英

How to find maximum value from array inside array of objects in mongodb

{
    "_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!

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"
        }
      }
    }
  }
])
  • $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM