Mongodb 有没有办法在同一个$项目中使用$filter和$sum?
假设我的聚合管道中有一个如下所示的文档:Mongodb 有没有办法在同一个$项目中使用$filter和$sum?,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,假设我的聚合管道中有一个如下所示的文档: { scores: [ {type: 'quiz', score: 75}, {type: 'quiz', score: 62}, {type: 'final', score: 34}, ] } 我正在使用$project来转换它,我想得到测验分数的总和,是否有一种方法可以将我的$filter和$sum链接起来 我知道我可能会使用两个$projects,但我目前设置管道的方式将迫使我在第二个项目中继续重新投影大量密钥,我
{
scores: [
{type: 'quiz', score: 75},
{type: 'quiz', score: 62},
{type: 'final', score: 34},
]
}
我正在使用$project
来转换它,我想得到测验分数的总和,是否有一种方法可以将我的$filter
和$sum
链接起来
我知道我可能会使用两个$project
s,但我目前设置管道的方式将迫使我在第二个项目中继续重新投影大量密钥,我希望避免这种情况。是的
db.collection.aggregate([
{ "$project": {
"totalQuiz": {
"$sum": {
"$filter": {
"input": "$score",
"as": "s",
"cond": { "$eq": [ "$$s.type", "quiz" ] }
}
}
}
}
])
您需要另一个操作员的帮助,该操作员将嵌入文档的分数映射到一个可以的值数组中。您可以使用操作符执行此操作,如下所示:
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
}
我认为$FASE会返回数组,而$SUM不会考虑数组。summation@ParshuramOP正在使用MongoDB 3.2检查。哦,但是作者使用的是什么版本?作者正在使用3.2。我知道这是因为在3.2中是新的,所以在嵌套属性的情况下,它给出了0。虽然Styvane的答案是对我所问文档的更直接的解决方案,但即使分数数组中有其他数值,您的解决方案仍然有效,我就是这样。