如何从 MongoDB 的嵌套对象中获取特定细节

How to get particular details from nested object from MongoDB

我正在 MongoDB 中为基于 NestJs 的网络应用程序保存数据。

我的MongoDB数据是这样的

"gameId": "1a2b3c4d5e"
"rounds": [
    {
      "matches": [
        {
          "match_id": "1111abc1111",
          "team1": {
            "team_id": "team8",
            "score": 0
          },
          "team2": {
            "team_id": "team2",
            "score": 0
          }
        },
        {
          "match_id": "2222abc2222",
          "team1": {
            "team_id": "team6",
            "score": 0
          },
          "team2": {
            "team_id": "team5",
            "score": 0
          }
        },
      ]
    }
  ]

这里我们有每场比赛的gameId,每场比赛都有很多轮和很多场比赛。每场比赛都有match_id。如何获取特定的比赛信息并根据 gameId & match_id 进行编辑? (N.B:我愿意根据match_id更新分数)

我试过这样的东西

    const matchDetails = await this.gameModel.findOne({
      gameId: gameId,
      rounds: { $elemMatch: { match_id: match_id } },
    });

但这不起作用并且 returns null。如何正确执行此操作?

问题是您在 rounds 数组上应用 elemMatch,但它应该在 rounds.matches 上。将您的查询更改为以下将解决问题:

const matchDetails = await this.gameModel.findOne({
      gameId: gameId,
      "rounds.matches": { $elemMatch: { match_id: match_id } },
});

编辑: 要仅获取特定的匹配元素,您可以使用 $unwind$filter:

的简单聚合
db.collection.aggregate([
  {
    "$match": {
      "gameId": gameId,
      "rounds.matches": { $elemMatch: { match_id: match_id } }
    }
  },
  {
    "$unwind": "$rounds"
  },
  {
    $project: {
      match: {
        $filter: {
          input: "$rounds.matches",
          as: "match",
          cond: {
            $eq: [
              "$$match.match_id",
              match_id 
            ]
          }
        }
      },
      _id: 0
    }
  }
])

示例 mongoplayground