MongoDB得到dictfield / embedded文件的平均值

时间:2014-10-19 04:51:03

标签: mongodb aggregation-framework mongoengine

我有一个像这样的MongoDB文档:

{
  ...
  score: 200,
  timing: {
    rT: 124
  },
  utc_timestamp: ISODate("2014-10-19T04:45:04.772Z")
}

我可以使用此查询获得score的平均值:

System._get_collection().aggregate([
            { "$match": {
                "system_id": system.id,
                "utc_timestamp": {
                    "$gte": datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) - datetime.timedelta(days=1),
                    "$lt": datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
                }
            }},
            { "$group": {
                "_id": { "$dayOfYear": "$utc_timestamp" },
                "delay": { "$avg": "$score" },
                "up": {
                    "$sum": { "$cond": [
                        { "$eq": [ "$result", 405 ]}, 1, 0
                    ]}
                },
                "total_count": { "$sum": 1 }
            }},
            { "$project": {
                "airtime": {
                    "$cond": [
                        { "$eq": [ "$up", 0 ] },
                        0,
                        { "$multiply" : [{"$divide": [ "$up", "$total_count" ]}, 100] }
                    ]
                },
                "delay": 1
            }}
        ])

注意这一行:

"delay": { "$avg": "$score" },

如何通过rT词典中的timing字段获得平均值?

这不起作用:

{ "$avg": "$timing.rT" }

1 个答案:

答案 0 :(得分:0)

{ "$avg": "$timing.rT" }的语法是正确的,应该可以正常工作。