首页 > 解决方案 > 使用 mongodb 进行聚合

问题描述

我们在 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}

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

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

标签: mongodbaggregation

解决方案


这应该这样做:

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

推荐阅读