我们在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}我们正在尝试聚合,但没有得到这样的结果。
你知道如何解决这个问题吗?
发布于 2019-01-09 21:06:06
这应该可以做到:
db.collection.aggregate([
{
$group: {
_id: "$idTeam",
matches: {
$addToSet: "$matchId"
}
}
},
{
$project: {
_id: 0,
idTeam: "$_id",
sumMatches: {
$size: "$matches"
}
}
}
])https://stackoverflow.com/questions/54110324
复制相似问题