2017-06-18 24 views
-3

我有以下收集結構,我希望找到每個學生的最低分數。

>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 
     } 
    ] 
} 

我使用aggregate命令

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。

+0

你正在做的MongoDB大學課程M101哪些語言具體問題是*「找到最低分和刪除它..」*(解釋,但這是要點)。在課程材料中這是一個問題的想法是你自己解決問題,而不是從StackOverflow中獲得答案。如果你能查找它,也會挫敗任何人的回答。你不覺得嗎? –

回答

0

經過一番搜索,我發現解決方案是在scores.score上添加$ unwind。完整的命令是:

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