MongoDB在嵌套集合中的平均值

时间:2017-04-08 21:58:58

标签: mongodb meteor

我试图计算许多测试中测试结果的平均分数,但是文档嵌套在person对象中的两个级别。

我无法获得嵌套集合中的平均值

{ "name" : "Person Name",
"tests" : [ 
    {
        "testID" : "01"
        },
        "scores" : {
            "math" : 3.0,
            "science" : 2.0
        }
    }
]
}
下面的

是我的mongoDB查询。

    db.students.aggregate([
   {
     $project: {
       mathAve: { $avg: "$math"},
       scienceAve: { $avg: "$science" },
     }
   }
])

1 个答案:

答案 0 :(得分:1)

有几种方法可以解决单人文档的问题。

以下查询$divide两个操作数,$reduce<div class="form-group"> <label for="textNome" class="control-label">Type text</label> </div> <div class="radio"> <label><input type="radio" name="mode" value="one" checked /> Selection 1</label> <input id="end" class="form-control" type="text"> </div> <div class="radio"> <label><input type="radio" name="mode" value="two"checked /> Selection 2</label> <input id="end" class="form-control" type="text"> </div> 文档加到其字段(testsmath)值的总和后跟{ {3}} science数组来计算平均值。

$size $和$$分别引用字段/聚合运算符/聚合阶段和内部变量。

Mongo版本&gt; = 3.4

tests

Mongo Version = 3.2

以下查询Expressionsdb.students.aggregate({ $project: { mathAve: {$divide:[{ $reduce: { input: "$tests.scores.math", initialValue: 0, in: { $sum: [ "$$value", "$$this" ] } } }, {$size:"$tests"}]}, scienceAve: {$divide:[{ $reduce: { input: "$tests.scores.science", initialValue: 0, in: { $sum: [ "$$value", "$$this" ] } } }, {$size:"$tests"}]} } }) 文档,后跟$unwind来计算每个字段的$group

tests
相关问题