2015-05-04 12 views
0

我有一個文件是這樣的:集團和比賽彙集起來的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.

我怎樣才能做到這一點?

回答

0

如果你只是想一個對經緯度,你可能會使用$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,但我認爲在這裏使用它沒有太大的好處。

最後,在$ group階段使用$ first [resp:$ last]時,引用文檔:「,$ group階段應該遵循$ sort階段,以便按照定義的順序輸入文檔。但根據你的描述,這裏不需要。

+0

哦哇,非常簡單!謝啦 – sachitad