分组和比赛聚合MongoDB

分组和比赛聚合MongoDB,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有这样的文件: { u '_id': ObjectId('5534cd32e4b0d5f14e6aa27d'), u 'geoip': { u 'coordinates': [-96.8353, 32.9299 ], u 'region_name': u 'TX', u 'latitude': 32.9299, u 'ip': u '173.193.154.240', u 'area_code': 972, u 'continen

我有这样的文件:

{
u '_id': ObjectId('5534cd32e4b0d5f14e6aa27d'),
u 'geoip': {
  u 'coordinates': [-96.8353,
      32.9299
    ],
    u 'region_name': u 'TX',
    u 'latitude': 32.9299,
    u 'ip': u '173.193.154.240',
    u 'area_code': 972,
    u 'continent_code': u 'NA',
    u 'country_code3': u 'USA',
    u 'country_code2': u 'US',
    u 'city_name': u 'Dallas',
    u 'longitude': -96.8353,
    u 'timezone': u 'America/Chicago',
    u 'country_name': u 'UnitedStates',
    u 'postal_code': u '75244',
    u 'real_region_name': u 'Texas',
    u 'dma_code': 623,
    u 'location': [-96.8353,
      32.9299
    ]
},
u 'dest_ip': u '173.193.154.240'
}
我想要达到的是<代码>按国家/地区名称分组

期望输出:

{
  'country_name': 'US',
  'count': 110,
  'location': [10, 10]
}
我现在做的是:

db.collection.aggregate([
    {
        "$group": {
            "_id": {"country_name": "$geoip.country_name"},
            "count": {"$sum": 1},
            },

    }
])
这行得通,但没有告诉我位置。如果我想要位置,我会:

"_id": {"country_name": "$geoip.country_name", "location": "$geoip.location"}
但这里的问题是,我们在同一个国家/地区有很多不同的地理位置。

所以,我想要的是
一个纬度和经度加上国家名称。

如何实现这一点?

如果您只需要一对经纬度,可以使用:

使用
$first
将保证经度和纬度都来自同一文档。也有一个,但我认为在这里使用它并没有多大好处

最后,引用文档:“在$group阶段中使用$first[resp:$last]时,$group阶段应跟随$sort阶段,以使输入文档按定义的顺序排列。”但根据您的描述,此处不需要这样做

db.collection.aggregate([
    {
        "$group": {
            "_id": {"country_name": "$geoip.country_name"},
            "count": {"$sum": 1},
            "longitude": {"$first": "$longitude"},              
            "latitude": {"$first": "$latitude"}
            }
    }
])