Misbach Imaduddin
Misbach Imaduddin

Reputation: 1

Aggregation Using Pymongo Within Daily Grouping

I am trying to create a script using pymongo to count several transaction like this :

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

I succeed to aggregate those data directly using MongoDB, here is the sample result:

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

But, I failed to aggregate those data using pymongo and got an error

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)

Here are my script :

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

Why does this error occur? What should I do? Thanks in advance.

Upvotes: 0

Views: 95

Answers (1)

Dmitry
Dmitry

Reputation: 2096

See the aggregate syntax http://api.mongodb.com/python/current/examples/aggregation.html You need to use [] for arguments.

Upvotes: 1

Related Questions