【问题标题】:Aggregation with mongodb使用 mongodb 进行聚合
【发布时间】:2019-01-09 21:06:05
【问题描述】:

我们正在 MongoDb 中保存每场比赛的球员统计数据。

{idPlayer: 27, idTeam: 6, matchId: 1, score: 90},
{idPlayer:38, idTeam: 9, matchId:1, score: 6}, 
{idPlayer:5, idTeam:8, matchId:2, score: 20}

我们想知道一支球队参加了多少场比赛: 我们希望结果为:

{idTeam, sumMatches}

{idTeam: 8, sumMatches: 6}
{idTeam: 9, sumMatches: 4}

我们正在尝试聚合,但没有得到这个结果。

知道如何解决这个问题吗?

【问题讨论】:

    标签: mongodb aggregation


    【解决方案1】:

    应该这样做:

    db.collection.aggregate([
      {
        $group: {
          _id: "$idTeam",
          matches: {
            $addToSet: "$matchId"
          }
        }
      },
      {
        $project: {
          _id: 0,
          idTeam: "$_id",
          sumMatches: {
            $size: "$matches"
          }
        }
      }
    ])
    

    【讨论】:

    • 是的!非常感谢。这正是我们想要尝试的
    • 没问题,很高兴我能帮上忙 :)
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 2019-06-29
    • 2019-02-03
    • 2017-02-16
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多