2

私は 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)
4

1 に答える 1

3

mongodb 集約フレームワークのタスクのようです:

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

次のような結果が生成されます。

{
    "result" : [
        {
            "_id" : "US",
            "count" : 302000
        },
        {
            "_id" : "CA",
            "count" : 180000
        },
        ...
    ],
    "ok" : 1
}

pymongo を使用した同じクエリ:

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

それが役立つことを願っています。

于 2013-06-28T08:36:01.160 に答える