假设我的聚合管道中有一个文档,如下所示:
{
scores: [
{type: 'quiz', score: 75},
{type: 'quiz', score: 62},
{type: 'final', score: 34},
]
}
我在用着$project
来改变它,我想得到测验分数的总和,有没有一种方法可以以某种方式链接我的$filter
and $sum
.
我知道我可能会使用两个$project
s,但我目前设置管道的方式将迫使我继续在第二个项目中重新投影大量密钥,这是我想避免的。
您需要另一个运算符的帮助,将嵌入文档的分数映射到您可以使用的值数组中$sum https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#use-in-project-stage。您可以使用$map https://docs.mongodb.com/v3.2/reference/operator/aggregation/map/运算符如下:
db.test.aggregate([
{
"$project": {
"scores": 1,
"quiz_total": {
"$sum": {
"$map": {
"input": "$scores",
"as": "item",
"in": {
"$cond": [
{ "$eq": [ "$$item.type", "quiz" ] },
"$$item.score",
0
]
}
}
}
}
}
}
])
样本输出
{
"_id" : ObjectId("582ac9619602e37d2794acd3"),
"scores" : [
{
"type" : "quiz",
"score" : 75
},
{
"type" : "quiz",
"score" : 62
},
{
"type" : "final",
"score" : 34
}
],
"quiz_total" : 137
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)