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
How to aggregate sum in MongoDB to get a total count?
提问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: 12
respectively, how could I use MongoDB Aggregation Framework to return the total number, i.e. total: 25
.
如果我有3个文件wins: 5
,wins: 8
,wins: 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 $group
and $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 $wins
which just fetches the values of the wins
field from the grouped documents and sums them together.
在这种情况下,如果您想获得所有 的总和wins
,您需要使用$
语法引用字段名称,因为$wins
它只是wins
从分组文档中获取字段的值并将它们相加。
Count
数数
You can sum
other 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
,而不是总数。