2013-06-27 32 views
1

我使用PyMongo並擁有約500萬條目的集合。每個條目都有一個國家代碼字段。PyMongo統計

什麼是最優雅的方式(和最佳的性能代價?)獲得的統計數據,如:

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) 
+1

您能否在集合中顯示一個條目的示例? – alecxe

+0

好的,我已經加了一個。 – horace

+0

您想要爲每個'_country_code'字段獲取的數字是具有國家代碼的文檔數量? – alecxe

回答

3

看起來像它的mongodb aggregation framework任務:

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}}}]) 

希望有幫助。

+0

是的,看起來完全像我需要的!謝謝! – horace