MongoDB查询和计算嵌套数组元素的平均值

时间:2016-10-16 13:51:55

标签: mongodb mongodb-query

我有一个集合lanes,其中包含以下结构的文档。只有disttime个新文档发生变化。我想计算按l_id分组的所有车道的平均速度。

{
    _id: 1213,
    ab:[
        {
            l_id: 101,
            dist: 100,
            time: 100
        },
        {
            l_id: 102,
            dist: 140,
            time: 120
        },
        {
            l_id: 103,
            dist: 10,
            time: 10
        }
    ]
}
像这样:

{[
    {
        l_id: 101,
        avgspeed: 14
    },
    {
        l_id: 102,
        avgspeed: 19
    },
    {
        l_id: 103,
        avgspeed: 9
    }
]}

如何使用mongo聚合/展开查询来完成?

编辑1 :(如何做到结构如下)

{
    _id: 1213,
    ab:[
        {
            l_id: 101,
            data:[{
                dist: 100,
                time: 100
            }]
        },
        {
            l_id: 102,
            data:[{
                dist: 140,
                time: 120
            }]
        },
        {
            l_id: 103,
            data:[{
                dist: 10,
                time: 10
            }]
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

import numpy as np
import matplotlib.pyplot as plt

t= np.linspace(60, 180,100)
ax= plt.subplot()
ax.plot(data.Weight, data.Height , color = 'red')
ax.plot(t, 60+ 0.05*t, label=r"$Height = 60+ 0.05*Weight$")
ax.plot(t, 50+ 0.16*t, label=r"$Height = 50+ 0.16*Weight$")
ax.set_xlabel(r'$Weight$', fontsize=12)
ax.set_ylabel(r'$Height$', fontsize=12)
ax.set_title('Dependence')

plt.show()