2017-04-08 86 views
0

我试图计算跨许多测试的测试结果的平均分数,但是文档在人物对象内嵌套了两个级别。下面MongoDB在嵌套集合中的平均值

我不能嵌套集合

{ "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

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

的下面查询$divide的两个操作数由$reduce荷兰国际集团的文件tests总结其字段(mathscience)值,随后tests$size阵列来计算平均的。

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

蒙戈版> = 3.4

db.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"}]} 
    } 
}) 

蒙戈版= 3.2

的下面查询$unwind S中的文档tests随后$group计算每个场的$avg

db.students.aggregate( 
{$unwind:"$tests"}, 
{$group: { 
     _id:null, 
     mathAve: { $avg: "$tests.scores.math"}, 
     scienceAve: { $avg: "$tests.scores.science" } 
    } 
})