如何在MongoDB中汇总总和以获得总计数? [英] How to aggregate sum in MongoDB to get a total count?

查看:411
本文介绍了如何在MongoDB中汇总总和以获得总计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些字段为{ wins: Number }的集合,我如何使用 MongoDB Aggregation Framework 获取集合中所有文档的获胜总数?

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

如果我有3个文档分别为wins: 5wins: 8wins: 12,如何使用MongoDB Aggregation Framework返回总数,即total: 25.

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.

推荐答案

总和

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

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

在这种情况下,如果要获取所有wins的总和,则需要使用$语法以$wins的形式引用字段名称,该语法仅获取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.

您也可以通过传递特定值(如您在注释中所做的那样)来sum其他值.如果您有

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

{ "$sum" : 1 }

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

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

这篇关于如何在MongoDB中汇总总和以获得总计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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