Q:

PyMongo query gives me back a nested DataFrame

I perform an aggregation with on a very large dataset. This is my code:
pipeline = [{"$match": {"Name_md_group": "ZEITUNGEN"}}, {"$group": {"_id": {"Name_freq": "$Name_freq"}, "total": {"$sum": "$Cost"}}}]
result = pd.DataFrame(list(collection.aggregate(pipeline)))

Result:
                                          _id         total
    0  {'Name_freq': 'WOECHENTLICH FUENFMAL'}  2.074940e+07
    1               {'Name_freq': 'SONSTIGE'}  2.284889e+07
    2           {'Name_freq': 'WOECHENTLICH'}  8.522535e+07
    3               {'Name_freq': 'TAEGLICH'}  3.700943e+07
    4  {'Name_freq': 'WOECHENTLICH SECHSMAL'}  1.489394e+09

Somehow I get back a nested object? Why is that and is there a way to get rid of it? The column name _id should be Name_freq. Can anyone help me?

A:

Put the expression directly into _id and add an extra $project stage.
pipeline = [
  { $match: { Name_md_group: "ZEITUNGEN" } },
  { $group: { _id: "$Name_freq", total: { $sum: "$Cost" } } },
  { $project: { Name_freq: "$_id", _id: 0, total: 1 }}
]

