分组和匹配聚合 MongoDB

Group and Match aggregrate MongoDB

我有这样的文档:

{
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'
}

我想要实现的是... group by country name

期望的输出:

{
  '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"}

但是这里的问题是我们有很多位置(different latitude and longitude) in the same country_name.

所以,我想要的只是one latitude and longitude with the country name.

我怎样才能做到这一点?

如果你只想要一对纬度经度,你可以使用$first accumulator operator

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

使用$first 将保证经度和纬度都来自相同 文档。还有一个$last operator,不过我觉得用在这里用处不大。

最后,引用文档:"when using $first[resp: $last] in a $group stage, the $group stage should follow a $sort stage to have the input documents in a defined order." 但是根据你的描述,这里不需要。