簡體   English   中英

如何從 mongodb 中的對象數組中的數組中找到最大值

[英]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"
            }
        }]
    }]
}

我有一個游戲系統的以下 mongodb 架構。我想寫一個查詢來找到每場比賽的最高分。 不知道該怎么辦!

不完全清楚每場比賽的最高得分是什么意思(什么是“比賽”),但一個簡單的解決方案是:

db.collection.aggregate([
  {
    $addFields: {
      max_score: {
        $max: {
          $max: "$achievement.players.score"
        }
      }
    }
  }
])
  • $map迭代achievement.players.score .players.score 循環並從數組數組中獲取最大值
  • $max從數組中獲取最大數
db.collection.aggregate([
  {
    $addFields: {
      maxScore: {
        $max: {
          $map: {
            input: "$achievement.players.score",
            in: { $max: "$$this" }
          }
        }
      }
    }
  }
])

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM