2016-03-05 26 views
0

我也有類似的這些存儲在我的數據庫文件:聚集在嵌入文檔和獨特的價值數

[ 
    { 
    "location_path": { 
     "Country": "US", 
     "State": "Illinois", 
     "City": "Chicago" 
    }, 
    "myvalue": 1 
    }, 
    { 
    "location_path": { 
     "Country": "US", 
     "State": "Houston", 
     "City": "Texas" 
    }, 
    "myvalue": 4 
    }, 
    { 
    "location_path": { 
     "Country": "US", 
     "State": "Illinois", 
     "City": "Chicago" 
    }, 
    "myvalue": 2 
    } 
] 

我有一些問題,構建聚集$group階段組文件以相同的位置路徑得到每個組中遇到的每個唯一值myvalue。所以,我的預期產出會類似於:

{ 
    "location_path": { 
     "Country": "US", 
     "State": "Illinois", 
     "City": "Chicago" 
    }, 
    "myvalue": {1: 1, 2: 1} 
}, 
{ 
    "location_path": { 
     "Country": "US", 
     "State": "Houston", 
     "City": "Texas" 
    }, 
    "myvalue": {4: 1} 
} 

我該如何實現類似於我想要的功能?到目前爲止,我有這個作爲我$group階段:

{ 
    '$group': { 
     '_id': { 
      'location_path': '$location_path', 
      'option': '$myvalue' 
     }, 
     'count': {'$sum': 1} 
    } 
} 

這沒關係,如果結果是我所期望的有所不同,但location_pathmyvalue每個唯一值的計數是很重要的。

+0

'「myvalue」:{1:1,2:1}'沒有多大意義。 'count:2'怎麼樣? – styvane

回答

1
{ 
    '$group': { 
     '_id': { 'path': '$location_path', 'value': '$myvalue'}, 
     'count': {'$sum': 1} 
    }, 
    '$project': { 
     '_id': '$_id.path', 
     'myvalue': '$_id.value', 
     'count': '$count', 
    }, 
    '$group': { 
     '_id': '$_id', 
     'values': {'$push': {'myvalue': '$myvalue', 'count': '$count'}} 
    } 
}