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 }
Try grouping by null.
db.murders.aggregate([{$group: {_id:null, pop: {$avg:"$murders"} } }])
More-Info: mongo-average-aggregation-query-with-no-group
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With