计算mongodb个文档的平均值

Calculate the average value of a mongodb document

假设我有这样一个集合:

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

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

...

该合集向我们展示了美国所有城市的谋杀案数量。我想计算全国谋杀案的平均数。我尝试使用

$group:

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

但我得到的结果是各州的谋杀案:

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

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

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

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

我的问题是,如何对这个结果进行分组以计算出唯一的平均值?像这样:

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

尝试按 null 分组。

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

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