mongodb - 在 mongo 中查找百分比
问题描述
我有一个包含 2 个文档的集合,如下所示。
{
_id:1,
Score: 30,
Class:A,
School:X
}
{
Score:40,
Class:A,
School:Y
}
我需要帮助编写查询以找出如下分数的百分比
{
School:X,
Percent:30/70
}
{
School:Y
Percent:40/70
}
解决方案
这个输入:
var r =
[
{"school":"X", "class":"A", "score": 30}
,{"school":"Y", "class":"A", "score": 40}
,{"school":"Z", "class":"A", "score": 20}
,{"school":"Y", "class":"B", "score": 50}
,{"school":"Z", "class":"B", "score": 17}
];
运行此管道:
db.foo.aggregate([
// Use $group to gather up the class and save the inputs via $push
{$group: {_id: "$class", tot: {$sum: "$score"}, items: {$push: {score:"$score",school:"$school"}}} }
// Now we have total by class, so just "reproject" that array and do some nice
// formatting as requested:
,{$project: {
items: {$map: { // overwrite input array $items; this is OK
input: "$items",
as: "z",
in: {
school: "$$z.school",
pct: {$concat: [ {$toString: "$$z.score"}, "/", {$toString:"$tot"} ]}
}
}}
}}
]);
产生此输出,_id
其中Class
:
{
"_id" : "A",
"items" : [
{"school" : "X", "pct" : "30/90"},
{"school" : "Y", "pct" : "40/90"},
{"school" : "Z", "pct" : "20/90"}
]
}
{
"_id" : "B",
{"school" : "Y", "pct" : "50/67"},
{"school" : "Z", "pct" : "17/67"}
]
}
$unwind
如果您愿意,可以从这里开始。
推荐阅读
- javascript - 我的网页上的一些 javascript 函数可以工作,而另一些则不能。我该怎么办/
- azure - 如何使用 Azurite Emulator for Blazor 应用程序
- xamarin.forms - Xamarin XCT TabView - 可以将标题设置为滚动/滑动以查看更多标题而不是水平放置吗?
- javascript - 在反应中调用方法 onChange 表时不获取值排序器?(我用过分拣机:真)
- git - 带有日期范围(--after/--before)的 git log 无法列出所有提交
- python - 将上下文传递到注册表单
- ios - 相机在 wkwebview 中无法使用 swift
- azure - Azure 数据工厂,BlobEventsTrigger:使用作为动态内容的 scheduleTime 值配置 blob 路径
- r - 系统发育中的最大似然/分支长度
- three.js - Three.js Dragcontrols将对象从相机移动到场景