Skip to content

Instantly share code, notes, and snippets.

@zhangpengGenedock
Last active June 19, 2017 06:47
Show Gist options
  • Save zhangpengGenedock/92c46322a8de074dc76a43667c847494 to your computer and use it in GitHub Desktop.
Save zhangpengGenedock/92c46322a8de074dc76a43667c847494 to your computer and use it in GitHub Desktop.
mongodb pymongo collection group by example.py
start_date = str(get_format_date(begin_timestamp))
end_date = str(get_format_date(end_timestamp))
match = {
'date': {
'$gte': start_date,
'$lte': end_date,
}
}
groupby = ['account_name', 'region']
group = {
'_id': {key: ('$%s' % key) for key in groupby} or {'None': '$None'},
'fee': {'$sum': '$fee'},
'cost': {'$sum': '$cost'},
'system_size': {'$sum': '$system_size'},
'user_size': {'$sum': '$user_size'},
}
rets = db.gddata_daily_stats.aggregate(
[
{'$match': match},
{'$group': group},
]
)
for ret in rets['result']:
account_period = {
'account_name': ret['_id']['account_name'],
'region': ret['_id']['region'],
'fee': ret['fee'],
'cost': ret['cost'],
'system_size': ret['system_size'],
'user_size': ret['user_size'],
}
account_period_lists.append(account_period)
new_account_data_bill_dataframe = pandas.DataFrame(account_period_lists,
columns=['account_name', 'region', 'fee', 'cost',
'system_size', 'user_size'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment