【问题标题】:How to get particular details from nested object from MongoDB如何从 MongoDB 的嵌套对象中获取特定细节
【发布时间】:2022-01-06 04:35:54
【问题描述】:

我正在 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,在每场比赛中,有很多回合和很多比赛。每个匹配项都有 ma​​tch_id。如何获取特定的比赛信息并根据 gameIdma​​tch_id 对其进行编辑? (注意:我愿意根据 ma​​tch_id 更新分数)

我尝试过类似的方法

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

但这不起作用并返回 null。如何正确地做到这一点?

【问题讨论】:

    标签: node.js typescript mongodb mongoose nestjs


    【解决方案1】:

    问题是您在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 上的示例。

    【讨论】:

    • 没有按预期工作。返回所有匹配项。不是具有特定 match_id 的那个
    • 等等,你的意思是你只想得到匹配的数组元素?
    • 是的。我只想要与 match_id 匹配的特定匹配
    • 哦,好吧,看看我的更新。
    • 这行得通。尽管它变得比我预期的要复杂一些。但做的工作。知道如何更新团队内部的分数吗?
    猜你喜欢
    • 2016-03-11
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多