2016-01-06 19 views
0

我試圖建立的MongoDB文檔的格式如下直方圖:從MongoDB的構建直方圖Pymongo

{ 
    "_id":1 
    "Properties":[ 
    { 
     "type": "a" 
    }, 
    { 
     "type": "d" 
    } 
    ] 
} 

{ 
    "_id":2 
    "Properties":[ 
    { 
     "type": "c" 
    }, 
    { 
     "type": "a" 
    } 
    ] 
} 

{ 
    "_id":3 
    "Properties":[ 
    { 
     "type": "c" 
    }, 
    { 
     "type": "d" 
    } 
    ] 
} 

此示例中的輸出應該是:

A = 2

C = 2

d = 2

我此刻includ解決方法es查詢整個集合:

collection.find({}) 

然後使用python字典遍歷並累積數據。 我敢肯定,在MongoDB查詢本身中有更好的方法來做到這一點,我可以在單個查詢中實現這些數據嗎?

請注意,我不知道在執行查詢之前可能找到哪些「類型」。

回答

3

在這種情況下,你可以使用MongoDB的aggregation

進一步瞭解Aggregationhttps://docs.mongodb.org/manual/core/aggregation-introduction/

db.collection.aggregate([ 
    { $unwind : "$Properties" }, 
    { $group: { _id: "$Properties.type", count: { $sum: 1 } } } 
]); 

輸出:

{ 
    "result" : [ 
     { 
      "_id" : "c", 
      "count" : 2.0000000000000000 
     }, 
     { 
      "_id" : "d", 
      "count" : 2.0000000000000000 
     }, 
     { 
      "_id" : "a", 
      "count" : 2.0000000000000000 
     } 
    ], 
    "ok" : 1.0000000000000000 
} 

在Python:

from pymongo import MongoClient 

if __name__ == '__main__': 
    db = MongoClient().test 
    pipeline = [ 
     { "$unwind" : "$Properties" }, 
     { "$group": { "_id": "$Properties.type", "count": { "$sum": 1 } } } 
    ] 
    print list(db.collection.aggregate(pipeline)) 

輸出:

[{u'count': 2, u'_id': u'c'}, {u'count': 2, u'_id': u'd'}, {u'count': 2, u'_id': u'a'}] 
1

不知道這是否能適合您的方案,但你可以做他們的財產分開,如:

count_a = collection.find({'Properties.type':'a'}).count() 
count_b = collection.find({'Properties.type':'b'}).count() 
count_c = collection.find({'Properties.type':'c'}).count() 

如果你不知道類型創建,將採取不同的類型,可以只是一個變量,這樣做:

mistery_type = 'assign the misery type in var when you know it' 
mistery_type_count = collection.find({'Properties.type': mistery_type}).count() 
+0

我會將其添加到問題 - 我不知道在執行查詢之前可能會遇到哪些類型。 – GalB1t

+1

這就是你所需要的我想 –

+0

我也編輯了我的答案與另一個例子,你可以把你的類型在一個變量,並更靈活的計數。 –