Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyMongo统计_Python_Mongodb_Statistics_Pymongo - Fatal编程技术网

Python PyMongo统计

Python PyMongo统计,python,mongodb,statistics,pymongo,Python,Mongodb,Statistics,Pymongo,我正在使用PyMongo,有一个大约500万条的收藏。每个条目都有一个国家代码字段 获得以下统计数据的最优雅的方式(以及最佳性能方面的方式)是什么: US - 302000 CA - 180000 IN - 160000 DE - 125000 ... MongoDB对此是否有一种特殊的查询,还是应该使用普通Python字典在循环中进行查询 编辑: 条目示例: update( {"id": user["id"]}, {"$set": { ... some oth

我正在使用PyMongo,有一个大约500万条的收藏。每个条目都有一个国家代码字段

获得以下统计数据的最优雅的方式(以及最佳性能方面的方式)是什么:

US - 302000
CA - 180000
IN - 160000
DE - 125000
...
MongoDB对此是否有一种特殊的查询,还是应该使用普通Python字典在循环中进行查询

编辑: 条目示例:

update(
    {"id": user["id"]},
    {"$set": {
        ... some other fields
        "_country_code": "US",
        "_last_db_update": datetime.datetime.utcnow()}
    }, upsert=True)

看起来这是一项针对以下人员的任务:

将产生如下结果:

{
    "result" : [
        {
            "_id" : "US",
            "count" : 302000
        },
        {
            "_id" : "CA",
            "count" : 180000
        },
        ...
    ],
    "ok" : 1
}
使用pymongo执行相同的查询:

db.command('aggregate', 'collection', pipeline=[{"$group": {"_id": "$_country_code", "count": {"$sum": 1}}}])

希望对您有所帮助。

您能展示一个集合中条目的示例吗?好的,我已经添加了一个。您试图为每个
\u country\u code
字段获取的数字就是有多少带有国家代码的文档?是的!但解决方案应该是完全动态的。我不知道包括哪些国家。是的,看起来正是我需要的!非常感谢。
db.command('aggregate', 'collection', pipeline=[{"$group": {"_id": "$_country_code", "count": {"$sum": 1}}}])