我想计算一名足球运动员在球场上的位置与他们所属国家的百分比。比方说,尼泊尔总共有800名球员,而只有20名是守门员,所以尼泊尔的比例是2.5%
我的数据集
[{
"position":"defenser",
"country":"Nepal"
},
{
"position":"defenser",
"country":"Nepal"
},
{
"position":"goal keeper",
"country":"Nepal"
},
{
"position":"goal keeper",
"country":"France"
},
{
"position":"defenser",
"country":"France"
},
{
"position":"goal keeper",
"country":"France"
},
{
"position":"defenser",
"country":"France"
},
{
"position":"defenser",
"country":"Nepal"
}
]
总共4名防守队员中有3名来自尼泊尔,4名防守球员中有2名来自法国。
预期输出:
{"country":"Nepal", "position": "defenser", "percentage":"75"}
{"country":"France", "position": "defenser", "percentage":"50"}
查询
- 按国家和位置分组,并计数
- 按国家分组,以计算该国家的totalSum
- 将计数/totalSum和*100进行除法运算的映射
- 展开并替换根部
- 结果是,对于每个国家,每个职位所占的百分比
Playmongo
aggregate(
[{"$group":
{"_id": {"country": "$country", "position": "$position"},
"sum": {"$sum": 1}}},
{"$group":
{"_id": "$_id.country",
"players": {"$push": "$$ROOT"},
"totalsum": {"$sum": "$sum"}}},
{"$set":
{"players":
{"$map":
{"input": "$players",
"in":
{"position": "$$this._id.position",
"country": "$_id",
"percentage":
{"$multiply":
[{"$divide": ["$$this.sum", "$totalsum"]}, 100]}}}}}},
{"$unwind": "$players"}, {"$replaceRoot": {"newRoot": "$players"}}])
就这个数据集和问题而言,我们可以在不使用$$ROOT和$replaceRoot函数的情况下获得适当的结果。
解决方案:
- 按国别分组,求总推位
- 然后展开位置阵列
3然后是多组国家和职位以及个人总和
4在最后一个项目阶段计算的百分比
db.collection.aggregate([{
$group: {
_id: '$country',
sum: {
$sum: 1
},
position: {
$push: '$position'
}
}
}, {
$project: {
_id: 0,
country: '$_id',
sum: 1,
position: 1
}
}, {
$unwind: {
path: '$position'
}
}, {
$group: {
_id: {
position: '$position',
country: '$country'
},
individualSum: {
$sum: 1
},
sum: {
$first: '$sum'
}
}
}, {
$project: {
_id: 0,
position: '$_id.position',
country: '$_id.country',
individualSum: 1,
sum: 1,
percentage: {
$multiply: [
{
$divide: [
'$individualSum',
'$sum'
]
},
100
]
}
}
}])