执行聚合以在 pymongo 中按组查找平均值时的编码问题
Encoding issue when performing aggregation to find average by group in pymongo
我在订单集合中有一个项目数据集:
> db.orders.find()
{"_id" : ObjectId("1a5"), "date": ISODate("2021-06-07T00:00:00Z"), "category": "A", "total": 150},
{"_id" : ObjectId("1a6"), "date": ISODate("2021-06-07T00:00:00Z"), "category": "B", "total": 175},
{"_id" : ObjectId("1a7"), "date": ISODate("2021-06-07T00:00:00Z"), "category": "A", "total": 200},
我想在 pymongo 中按类别查找总计的平均值。类别有时不存在,但总计始终存在。
我在 py 中试过了mongo
pipeline = [
{"$group": { "_id": "$category", "average": {"$avg": {"$total"}}}}
]
db.command('aggregate', 'orders', pipeline=pipeline, explain=True)
我收到一个错误
InvalidDocument: cannot encode object: {'$total'}, of type: <class 'set'>
在 mongo shell 中执行类似的查询直接工作正常:
> db.orders.aggregate([{$group: {_id: "$category", average: {$avg: "$total"}}}])
{ "_id" : "A", "average" : 175 }
{ "_id" : "B", "average" : 175 }
我使用 Compass 检查过 total 的值存储为 int32,所以我不明白错误消息以及如何修复它。我也尝试四处搜索,但我发现的关于此错误的大部分内容都是关于将条目插入数据库而不是聚合它们。我错过了什么吗?谢谢。
你周围有额外的大括号"$total"
;尝试:
pipeline = [
{"$group": { "_id": "$category", "average": {"$avg": "$total"}}}
]
我在订单集合中有一个项目数据集:
> db.orders.find()
{"_id" : ObjectId("1a5"), "date": ISODate("2021-06-07T00:00:00Z"), "category": "A", "total": 150},
{"_id" : ObjectId("1a6"), "date": ISODate("2021-06-07T00:00:00Z"), "category": "B", "total": 175},
{"_id" : ObjectId("1a7"), "date": ISODate("2021-06-07T00:00:00Z"), "category": "A", "total": 200},
我想在 pymongo 中按类别查找总计的平均值。类别有时不存在,但总计始终存在。
我在 py 中试过了mongo
pipeline = [
{"$group": { "_id": "$category", "average": {"$avg": {"$total"}}}}
]
db.command('aggregate', 'orders', pipeline=pipeline, explain=True)
我收到一个错误
InvalidDocument: cannot encode object: {'$total'}, of type: <class 'set'>
在 mongo shell 中执行类似的查询直接工作正常:
> db.orders.aggregate([{$group: {_id: "$category", average: {$avg: "$total"}}}])
{ "_id" : "A", "average" : 175 }
{ "_id" : "B", "average" : 175 }
我使用 Compass 检查过 total 的值存储为 int32,所以我不明白错误消息以及如何修复它。我也尝试四处搜索,但我发现的关于此错误的大部分内容都是关于将条目插入数据库而不是聚合它们。我错过了什么吗?谢谢。
你周围有额外的大括号"$total"
;尝试:
pipeline = [
{"$group": { "_id": "$category", "average": {"$avg": "$total"}}}
]