Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the average value of a mongodb document [duplicate]

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 }
like image 977
user1603268 Avatar asked Apr 20 '15 19:04

user1603268


1 Answers

Try grouping by null.

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

More-Info: mongo-average-aggregation-query-with-no-group

like image 117
jzapata Avatar answered Oct 02 '22 17:10

jzapata