mongodb 如何在MongoDB中汇总总和以获得总数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17044587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:16:55  来源:igfitidea点击:

How to aggregate sum in MongoDB to get a total count?

mongodbaggregation-framework

提问by Sahat Yalkabov

For some collection with a field { wins: Number }, how could I use MongoDB Aggregation Frameworkto get the total number of wins across all documents in a collection?

对于某些带有字段的集合,{ wins: Number }我如何使用MongoDB 聚合框架来获取集合中所有文档的总获胜次数?

Example:

例子:

If I have 3 documents with wins: 5, wins: 8, wins: 12respectively, how could I use MongoDB Aggregation Framework to return the total number, i.e. total: 25.

如果我有3个文件wins: 5wins: 8wins: 12分别,我怎么可能使用MongoDB的聚合框架返回的总数,即total: 25

回答by WiredPrairie

Sum

To get the sum of a grouped field when using the Aggregation Framework of MongoDB, you'll need to use $groupand $sum:

要在使用 MongoDB 的聚合框架时获取分组字段的总和,您需要使用$group$sum

db.characters.aggregate([ { 
    $group: { 
        _id: null, 
        total: { 
            $sum: "$wins" 
        } 
    } 
} ] )

In this case, if you want to get the sum of all of the wins, you need to refer to the field name using the $syntax as $winswhich just fetches the values of the winsfield from the grouped documents and sums them together.

在这种情况下,如果您想获得所有 的总和wins,您需要使用$语法引用字段名称,因为$wins它只是wins从分组文档中获取字段的值并将它们相加。

Count

数数

You can sumother values as well by passing in a specific value (as you'd done in your comment). If you had

您也可以sum通过传入特定值来获取其他值(就像您在评论中所做的那样)。如果你有

{ "$sum" : 1 },

{ "$sum" : 1 },

that would actually be a count of all of the wins, rather than a total.

这实际上是所有 的计数wins,而不是总数。