有没有办法在同一个$ project中使用$ filter和$ sum? [英] Is there any way to use $filter and $sum in the same $project?

查看:82
本文介绍了有没有办法在同一个$ project中使用$ filter和$ sum?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的汇总管道中有一个文档,如下所示:

Let's say I have a document in my aggregate pipeline that looks like this:

{
  scores: [
    {type: 'quiz', score: 75},
    {type: 'quiz', score: 62},
    {type: 'final', score: 34},
  ]
}

我正在使用$project对其进行转换,并且我想获得测验分数的总和,是否可以通过某种方式将我的$filter$sum链接起来.

I'm using $project to transform it, and I'd like to get the sum of the the quiz scores, is there a way I could somehow chain my $filter and $sum.

我知道我可能会使用两个$project,但是我目前正在建立管道的方式将迫使我继续在第二个项目中重新投影大量的键,这是我想避免的.

I know that I could potentially use two $projects, but the way I currently have my pipeline set up would force me to continue reproject a ton of keys in my second project, which I'd like to avoid.

推荐答案

是!

db.collection.aggregate([ 
    { "$project": { 
        "totalQuiz": { 
            "$sum": { 
                "$filter": {
                    "input": "$score", 
                    "as": "s",
                    "cond": { "$eq": [ "$$s.type", "quiz" ] }
                }
             }
        }
    }
])

这篇关于有没有办法在同一个$ project中使用$ filter和$ sum?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆