繁体   English   中英

使用Pymongo从MongoDB构建直方图

[英]Building a histogram from MongoDB with Pymongo

我正在尝试以以下格式创建MongoDB文档的直方图:

{
    "_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

目前,我的解决方法包括使用以下方法查询整个集合:

collection.find({})

然后使用python字典遍历和累积数据。 我确定在MongoDB查询本身中有更好的方法可以执行此操作,我是否可以怀疑单个查询即可获得这些数据?

请注意,在执行查询之前,我不知道可以找到哪些“类型”。

在这种情况下,您可以使用MongoDB aggregation

有关Aggregation更多信息: https : //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'}]

不知道这是否适合您的情况,但是您可以按属性分别将它们分开,例如:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM