mongodb - 使用 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}
我们正在尝试聚合,但没有得到这个结果。
知道如何解决这个问题吗?
解决方案
这应该这样做:
db.collection.aggregate([
{
$group: {
_id: "$idTeam",
matches: {
$addToSet: "$matchId"
}
}
},
{
$project: {
_id: 0,
idTeam: "$_id",
sumMatches: {
$size: "$matches"
}
}
}
])
推荐阅读
- python - 从数组python复制x>a元素
- php - 找不到保存功能
- python - 从列表中查找至少包含 3 个元音的单词
- java - 如何制作文件实例和进度阅读栏
- python - 我可以使用flutter和python在同一个firebase实时数据库上读写数据吗?
- python - 如何从 yolo 检测中制作稳定的视频
- html - 如何使用来自html的异步管道获取可观察对象的嵌套值
- arduino - 数组中的随机颜色
- javascript - 从磁盘读取文件时出错:错误:ENOENT:没有这样的文件或目录,打开'./database.json
- javascript - 使用 console.log / console.table 以不同的顺序显示数据