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

编程入门 行业动态 更新时间:2024-10-23 14:21:03
本文介绍了如何在 MongoDB 中汇总总和以获得总计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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: 5、wins: 8、wins: 12,我该如何使用 MongoDB 聚合框架返回总数,即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.

推荐答案

Sum

使用 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 中汇总总和以获得总计数?

本文发布于:2023-11-22 19:33:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   如何在   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!