2016-01-06 20 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

我也编辑了我的答案与另一个例子,你可以把你的类型在一个变量,并更灵活的计数。 –