2016-11-15 71 views
2

比方說,我有我的總管道的文件,看起來像這樣:

{ 
    scores: [ 
    {type: 'quiz', score: 75}, 
    {type: 'quiz', score: 62}, 
    {type: 'final', score: 34}, 
    ] 
} 

我使用$project改造它,我想獲得的測驗分數的總和,是有我可以以某種方式鏈接我的$filter$sum

我知道我可以使用兩個$project s,但現在我的管道設置的方式會迫使我繼續在我的第二個項目中重新投影一噸密鑰,這是我想避免的。

回答

1

是的!

db.collection.aggregate([ 
    { "$project": { 
     "totalQuiz": { 
      "$sum": { 
       "$filter": { 
        "input": "$score", 
        "as": "s", 
        "cond": { "$eq": [ "$$s.type", "quiz" ] } 
       } 
      } 
     } 
    } 
]) 
+0

我想$過濾器會返回一個數組和$總和將不考慮數組求和 –

+1

@Parshuram OP正在使用MongoDB 3.2檢查[發佈說明](https://docs.mongodb.com/manual/release-notes/3.2/#accumulator-expression-availability)。 – styvane

+0

哦,但作者使用什麼版本? –

2

您將需要從其他運營商即嵌入文檔的得分映射到值,你可以$sum陣列的幫助。你可以這樣做,使用$map操作,如下:

db.test.aggregate([ 
    { 
     "$project": { 
      "scores": 1, 
      "quiz_total": { 
       "$sum": { 
        "$map": { 
         "input": "$scores", 
         "as": "item", 
         "in": { 
          "$cond": [ 
           { "$eq": [ "$$item.type", "quiz" ] }, 
           "$$item.score", 
           0 
          ] 
         } 
        } 
       }     
      }  
     } 
    } 
]) 

樣本輸出

{ 
    "_id" : ObjectId("582ac9619602e37d2794acd3"), 
    "scores" : [ 
     { 
      "type" : "quiz", 
      "score" : 75 
     }, 
     { 
      "type" : "quiz", 
      "score" : 62 
     }, 
     { 
      "type" : "final", 
      "score" : 34 
     } 
    ], 
    "quiz_total" : 137 
} 
+0

感謝您的回答。雖然Styvane的答案是我詢問的文檔的更直接的解決方案,但即使在score數組中存在其他數值(即我的情況),您的解決方案也能正常工作。 –

相關問題