2017-03-06 76 views
0

我想從json窗體中的一些OSM數據中收集一些見解。下面是我使用MongoDB中/ PyMongo文件的例子:MongoDB。如何通過聚合管道傳輸計算字段?

{"amenity": "post_office", 
"name": "Dominion Road Postshop", 
"created": {"uid": "10829", 
      "changeset": "607706", 
      "version": "5", 
      "user": "myfanwy", 
       "timestamp": "2007-11-24T12:41:04Z"}, 
"pos": [-36.8801299, 174.7495053], 
"created_by": "Potlatch 0.5d", 
"type": "node", 
"id": "61076379"} 

所以每個文件都有一個用戶和市容。我想查找每個用戶記錄的每個舒適度的計數,除以每個用戶記錄的舒適度的總量。

因此,爲了幫助澄清這裏的代碼段我會用它來尋找每個個體數:

查詢1.找到多少各設施的每個用戶記錄:

amenity_per_user = coll.aggregate([{"$match":{"amenity":{"$exists":True}}}, 
           {"$group":{"_id":{"user":"$created.user", "amenities":"$amenity"}, "count":{"$sum":1}}}, 
           {"$sort":{"count":-1}}]) 

查詢2。找到多少設施,每個用戶記錄:

results = coll.aggregate([{"$match":{"amenity":{"$exists":True}}}, 
         {"$group":{"_id":"$created.user", "count":{"$sum":1}}}, 
         {"$sort":{"count":-1}}]) 

而對於這兩個問題的答案是(僅限於每5個結果):

Finding how many of each amenity each user records: 
{u'_id': {u'amenities': u'parking', u'user': u'Rudy355'}, u'count': 1886} 
{u'_id': {u'amenities': u'post_box', u'user': u'Rudy355'}, u'count': 547} 
{u'_id': {u'amenities': u'telephone', u'user': u'Rudy355'}, u'count': 485} 
{u'_id': {u'amenities': u'parking', u'user': u'myfanwy'}, u'count': 451} 
{u'_id': {u'amenities': u'restaurant', u'user': u'Rudy355'}, u'count': 429} 
Find how many amenities each user records: 
{u'_id': u'Rudy355', u'count': 6321} 
{u'_id': u'myfanwy', u'count': 951} 
{u'_id': u'Robert Ancell', u'count': 599} 
{u'_id': u'lcmortensen', u'count': 366} 
{u'_id': u'Marks2000', u'count': 228} 

現在我想要做的是將每個用戶的最高舒適度(即,Rudy355爲停車舒適度設置1886個條目)的總量除以他們的錄音總量(查詢2)。 - 所以最終的結果是Rudy355在'停車'設施中錄製了0.3張他的錄音。 - 1886/6321 = 0.3。

這是我必須:

coll.aggregate([{"$match":{"amenity":{"$exists":True}}}, 
        {"$group":{"_id":"$created.user", "user_count":{"$sum":1}}}, 
        {"$group":{"_id":{"user":"$created.user", "amenities":"$amenity"}, "amenity_count":{"$sum":1}, 
           "ucount":{"$push":"$user_count"}}}, 
        {"$unwind":"$ucount"}, 
        {"$project":{"$divide":{"$ucount", "$amenity_count"}}}, 
        {"$sort":{"count":-1}}]) 

任何幫助將是真棒!

順便說我真的不喜歡使用$推保存「USER_COUNT」的價值理念。有誰知道保存計算字段的更好方法。

回答

0

您可以嘗試下面的聚合。 $push保存每個amenity及其count稍後用於與total用戶舒適次數計算record

[ 
    {"$match":{"amenity":{"$exists":True}}}, 
    {"$group":{"_id":{"user":"$created.user", "amenity":"$amenity"}, "count":{"$sum":1}}}, 
    {"$group":{"_id":"$_id.user", "total":{"$sum":"$count"}, "amenities":{"$push":{amenity:"$_id.amenity","count":"$count"}}}}, 
    {"$unwind":"$amenities"}, 
    {"$project:{"_id":0,"user":"$_id", "amenity":"$amenities.amenity", record":{"$divide":{"$amenities.count", "$total"}}}}, 
    {"$sort":{"record":-1}} 
]                               

您應該輸出如下。

{"user":"Rudy355", "amenity":"parking", "record":0.3} 
+0

謝謝。現在都在工作 –