如何在汇总$ group

时间:2017-06-18 07:41:43

标签: mongodb

我有以下收集结构,我想找到每个学生的最低分数。

>db.students.findOne()
{
    "_id" : 0,
    "name" : "aimee Zank",
    "scores" : [
        {
            "type" : "exam",
            "score" : 1.463179736705023
        },
        {
            "type" : "quiz",
            "score" : 11.78273309957772
        },
        {
            "type" : "homework",
            "score" : 6.676176060654615
        },
        {
            "type" : "homework",
            "score" : 35.8740349954354
        }
    ]
}

我使用下面的聚合命令

db.students.aggregate([
  {
    $group: {_id: "$_id" , min: {$min: '$scores.score'}}
  }
])

以下是输出:

{ "_id" : 199, "min" : [ 82.11742562118049, 49.61295450928224, 28.86823689842918, 5.861613903793295 ] }
{ "_id" : 198, "min" : [ 11.9075674046519, 20.51879961777022, 55.85952928204192, 64.85650354990375 ] }
{ "_id" : 95, "min" : [ 8.58858127638702, 88.40377630359677, 25.71387474240768, 23.73786528217532 ] }
{ "_id" : 11, "min" : [ 78.42617835651868, 82.58372817930675, 87.49924733328717, 15.81264595052612 ] }
{ "_id" : 94, "min" : [ 6.867644836612586, 63.4908039680606, 85.41865347441522, 26.82623527074511 ] }

它返回每个学生的所有分数而不是最小分数。我的查询命令有什么问题?我正在使用mongo 3.4。

1 个答案:

答案 0 :(得分:1)

经过一番搜索,我发现解决方案是在scores.score上添加$ unwind。完整的命令是:

stus = db.students.aggregate([
  {
    "$unwind": "$scores"
  },
  {
    $group: {_id: "$_id" , minScore: {$min: '$scores.score'}}
  }
])