Reputation: 147
I have a python script in which I'm using pymongo to aggregate collections and perform certain operations on them if the sum of a particular aggregate is greater than a number (in this case, 30).
agg = collection.aggregate([{"$match":{"valid":1}}, {"$group": {"_id": {"createdby" : "$createdby" ,"addedtime" : "$addedtime", "empname" : "$empname"}, "count":{"$sum":1}}}])
cnt = 0
for eachAgg in agg:
print "eachAgg = ",eachAgg
if eachAgg['count'] >= 30:
When I run this script, I'm getting
eachAgg = ok
Traceback (most recent call last):
File "test.py", line 33, in <module>
if eachAgg['count'] >= 30:
TypeError: string indices must be integers
I don't understand how $sum
aggregate is not an integer.
Upvotes: 3
Views: 557
Reputation: 5539
agg:
returns a more detailed dict with the result of aggregation i.e.:
{
u'ok': 1.0,
u'waitedMS': 0L,
u'result': [<your actual aggregation result>]
}
That's why you get TypeError: string indices must be integers
, cause you iterate over keys in the dict (for eachAgg in agg
) , where a key is string and string indices must be integers.
The real data result it is in agg['result']
, try:
for eachAgg in agg['result']:
if eachAgg['count'] >= 30:
....
Upvotes: 4