2016-12-28 81 views
0

我试图用pymongo来算几个交易这样创建一个脚本:聚合使用Pymongo在每日分组

{ 
    "_id" : ObjectId("58437604a966aec46dfa249f"), 
    "transaction_id" : 282932121, 
    "transaction_serial_number" : "GtgT46A", 
    "transaction_date" : ISODate("2015-09-28T00:00:00Z"), 
    "card_type" : "MC", 
    "transaction_nominal" : 3500 
} 
... 

我成功聚集直接使用MongoDB的这些数据,这里是抽样结果:

{ 
    "_id" : { 
     "card_type" : "MC", 
     "date" : ISODate("2015-09-28T00:00:00Z") 
    }, 
    "count" : 179011 
} 

但是,我没有使用pymongo汇总这些数据,就有了一个错误

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "script_aggregate.py", line 84, in <module> 
    cursor = db.transaction.aggregate(match, proj1, proj2, group); 
TypeError: aggregate() takes exactly 2 arguments (5 given) 

这是我的脚本:

from datetime import datetime 
from pymongo import MongoClient 

client = MongoClient('localhost', 27017) 
db = client['mydb'] 
collection = db['transaction'] 

match={"$match" : { 
       "transaction_date" : { "$gt" : datetime(2013,1,1).isoformat() } 
     } 
}; 

proj1={"$project" : { 
     "_id" : 0, 
     "transaction_date" : 1, 
     "card_type" : 1, 
     "h" : { 
      "$hour" : "$transaction_date" 
     }, 
     "m" : { 
      "$minute" : "$transaction_date" 
     }, 
     "s" : { 
      "$second" : "$transaction_date" 
     }, 
     "ml" : { 
      "$millisecond" : "$transaction_date" 
     } 
    } 
}; 

proj2={"$project" : { 
     "_id" : 0, 
     "card_type" : 1, 
     "transaction_date" : { 
      "$subtract" : [ 
       "$transaction_date", 
       { 
        "$add" : [ 
         "$ml", 
         { 
          "$multiply" : [ 
           "$s", 
           1000 
          ] 
         }, 
         { 
          "$multiply" : [ 
           "$m", 
           60, 
           1000 
          ] 
         }, 
         { 
          "$multiply" : [ 
           "$h", 
           60, 
           60, 
           1000 
          ] 
         } 
        ] 
       } 
      ] 
     } 
    } 
}; 

group={"$group" : { 
     "_id" : { 
      "card_type" : "$card_type", 
      "date" : "$transaction_date" 
     }, 
     "count" : { 
      "$sum" : 1 
     } 
    } 
}; 





cursor = db.transaction.aggregate(match, proj1, proj2, group); 

for document in cursor: 
    print(document); 

我该怎么办?在此先感谢

回答

1

请参阅aggregate语法http://api.mongodb.com/python/current/examples/aggregation.html 您需要使用[]作为参数。

+0

OMG my appologize,谢谢你提醒我。顺便说一句,我的脚本没有打印任何语法结果 'cursor = db.transaction.aggregate(match,proj1,proj2,group); 用于光标文档: print(document);' 你知道为什么@Dmitry? –

+0

它在MongoDB shell的情况下工作吗?尝试设置'match = {}' – Dmitry

+0

啊谢谢你,我认为我的关于''transaction_date“部分的脚本:{”$ gt“:datetime(2013,1,1).isoformat()}'仍然是越野车 –