使用Python操作MongoDB计算数组字段平均值返回null如何解决
问题原因
- 字段引用错误:MongoDB聚合操作中引用文档字段需要加
$前缀,你写的"Time"会被识别为普通字符串,而非字段值。即使修正为"$Time",还存在第二个问题。 $avg运算符默认行为是对多个文档的同字段数值做聚合,直接传入数组字段不会自动计算数组内部元素的平均值,因此返回null。
修正方案
你的需求是计算单个指定文档内三个数组各自的内部元素平均值,不需要使用$group,改用$match过滤目标文档+$project计算数组平均即可,MongoDB 3.2及以上版本支持$avg直接接收数组作为输入计算内部元素平均值。
修正后代码如下:
from bson.objectid import ObjectId @app.route('/sta') def sta(): docs = db.basetest.aggregate([ # 匹配指定_id的文档,注意_id是ObjectId类型,不能直接传字符串 {"$match": {"_id": ObjectId('618af03902cd107477e3f2b9')}}, # 计算三个数组的内部平均值 {"$project": { "_id": 1, "avg_Time": {"$avg": "$Time"}, "avg_yaw": {"$avg": "$yaw"}, "avg_pitch": {"$avg": "$pitch"} }} ]) for document in docs: # 将ObjectId转为字符串方便JSON序列化返回 document["_id"] = str(document["_id"]) return document
返回结果示例:
{ "_id": "618af03902cd107477e3f2b9", "avg_Time": 1374, "avg_yaw": 0.3, "avg_pitch": 0.7333333333333333 }
补充:若使用MongoDB 3.2以下版本,可通过
$unwind拆分数组后再聚合计算:from bson.objectid import ObjectId @app.route('/sta') def sta(): docs = db.basetest.aggregate([ {"$match": {"_id": ObjectId('618af03902cd107477e3f2b9')}}, {"$unwind": "$Time"}, {"$group": { "_id": "$_id", "avg_Time": {"$avg": "$Time"}, "yaw": {"$first": "$yaw"}, "pitch": {"$first": "$pitch"} }}, {"$unwind": "$yaw"}, {"$group": { "_id": "$_id", "avg_Time": {"$first": "$avg_Time"}, "avg_yaw": {"$avg": "$yaw"}, "pitch": {"$first": "$pitch"} }}, {"$unwind": "$pitch"}, {"$group": { "_id": "$_id", "avg_Time": {"$first": "$avg_Time"}, "avg_yaw": {"$first": "$avg_yaw"}, "avg_pitch": {"$avg": "$pitch"} }} ]) for document in docs: document["_id"] = str(document["_id"]) return document
内容的提问来源于stack exchange,提问作者youngt17
相关产品推荐
相关产品推荐

