$ sum:1在Mongo中是什么意思 [英] What does $sum:1 mean in Mongo

查看:202
本文介绍了$ sum:1在Mongo中是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个收藏集foo:

{ "_id" : ObjectId("5837199bcabfd020514c0bae"), "x" : 1 }
{ "_id" : ObjectId("583719a1cabfd020514c0baf"), "x" : 3 }
{ "_id" : ObjectId("583719a6cabfd020514c0bb0") }

我使用以下查询:

db.foo.aggregate({$group:{_id:1, avg:{$avg:"$x"}, sum:{$sum:1}}})

然后我得到一个结果:

{ "_id" : 1, "avg" : 2, "sum" : 3 }

{$sum:1}在此查询中是什么意思?

What does {$sum:1} mean in this query?

推荐答案

来自

在$ group阶段中使用时,$ sum具有以下语法,并返回所有数字值的总和,这些值的总和是将指定的表达式应用到按键共享同一组的一组文档中的每个文档:

When used in the $group stage, $sum has the following syntax and returns the collective sum of all the numeric values that result from applying a specified expression to each document in a group of documents that share the same group by key:

{$ sum:<表达式>}

{ $sum: < expression > }

由于在您的示例中,表达式为1,所以它将为组中的每个文档聚合一个值为1的值,从而得出每个组中文档的总数.

Since in your example the expression is 1, it will aggregate a value of one for each document in the group, thus yielding the total number of documents per group.

这篇关于$ sum:1在Mongo中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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