【发布时间】:2019-12-23 18:54:49
【问题描述】:
如何在 MongoDB 中对文档进行分组并获取其数量,以及获取子文档的平均数量。
收藏
[{
"type": "FeatureCollection",
"cityName": "Bengaluru",
"features": [
{
"type": "Feature",
"id": 2085,
"properties": {
"countryName": "India",
"continentName": "Asia"
}
},
{
"type": "Feature",
"id": 2085,
"properties": {
"countryName": "India",
"continentName": "Asia"
}
}
]
}
{
"type": "FeatureCollection",
"cityName": "Bengaluru",
"features": [
{
"type": "Feature",
"id": 2095,
"properties": {
"countryName": "India",
"continentName": "Asia"
}
}
]
}
{
"type": "FeatureCollection",
"cityName": "Bengaluru",
"features": [
{
"type": "Feature",
"id": 2035,
"properties": {
"countryName": "India",
"continentName": "Asia"
}
}
]
},
{
"type": "FeatureCollection",
"cityName": "Delhi",
"features": [
{
"type": "Feature",
"id": 2031,
"properties": {
"countryName": "India",
"continentName": "Asia"
}
}
{
"type": "Feature",
"id": 2032,
"properties": {
"countryName": "India",
"continentName": "Asia"
}
}
]
}
...
]
预期结果
[
{
"cityName": "Bengaluru",
"count": 3
"avgFeatures": 1
},
{
"cityName": "Delhi",
"count":1
"avgFeatures": 2
},
]
在上面的示例中,count: 1 根据 cityName 对数据进行分组。例如:db.mycollection.aggregate({$project: { count: { $size:"$features" }}}).
而 avg 仅具有按 cityName 分组的所有文档的平均 features 数组计数。
我们将不胜感激任何形式的帮助。
【问题讨论】:
-
为什么
Bengaluru的预期avgFeatures是1而不是1.33? -
请解释什么必须代表计数(和 avgFeature)
-
Count表示记录组,例如:存在 3 个cityName:Bengaluru对象。 & Avg 实际上是 1.33 对于班加罗尔我们可以做圆形吗?通过计算与分组对象相关的特征数组计数获得的平均值