计算一个mongodb文档的平均值 [英] Calculate the average value of a mongodb document

查看:24
本文介绍了计算一个mongodb文档的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的集合:

Suppose that I have a collection like this:

{
  _id: 1,
  city: "New York",
  state: "NY",
  murders: 328
}

{
  _id: 2,
  city: "Los Angeles",
  state: "CA",
  murders: 328
}

...

该系列向我们展示了美国所有城市的谋杀案数量.我想计算一下全国平均谋杀案.我尝试使用

The collection shows us the number of murders in all cities of USA. I'd like to calculate the average of murders in all the country. I tried to use

$group:

db.murders.aggregate([{$group: {_id:"$state", pop: {$avg:"$murders"} } }])

但我得到的结果是按州划分的谋杀案:

But I get as result the murders by state:

{ "_id" : "NY", "murders" : 200 }

{ "_id" : "NJ", "murders" : 150 }

{ "_id" : "CA", "murders" : 230 }

{ "_id" : "CT", "murders" : 120 }

我的问题是,如何将此结果分组以计算唯一平均值?像这样的:

My question is, how can I group this result to calculate an unique average? Something like this:

{ "_id" : "USA", "murders" : 175 }

推荐答案

尝试按null分组.

db.murders.aggregate([{$group: {_id:null, pop: {$avg:"$murders"} } }])

更多信息:mongo-average-aggregation-query-with-no-组

这篇关于计算一个mongodb文档的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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