Calculate the average value of a mongodb document [duplicate]

三世轮回 提交于 2019-11-28 10:09:19

问题


This question already has an answer here:

  • Mongo average aggregation query with no group 3 answers

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 }

回答1:


Try grouping by null.

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

More info



来源:https://stackoverflow.com/questions/29756262/calculate-the-average-value-of-a-mongodb-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!