2013-12-16 422 views
0

我有這種類型的文件:MongoDB的聚合管道

collection:People 
{name:"George", grade:5, school:"MathHighSchool"} 

,還有更多的例子。 我需要找到所有的人誰的查詢:在MathHighSchool(所以我們有db.people.aggregate({$match:{school:"MathHighSchool"}},....) 研究

,然後通過他們的年級組他們,因爲它顯示了人與品位與數人數等級在3到5之間 以及等級大於等於5的人數。任何想法?

+1

[你做了什麼研究?](https://www.google.de/search?q=mongodb+group) – Philipp

+0

你是什麼意思?我一直在嘗試2個小時左右。 – user3108836

+0

{$ group:{_ id:「$ grade」,low:{$ lt:3},medium:{$ and:[{lte:5},{gte:3}],high:{gt:5}} }})像這樣的東西,但does not; t工作 – user3108836

回答

4

爲了有條件地對$group管道步驟中的匹配進行求和,您需要使用$cond operator

測試數據設置:

db.people.insert([ 
    {name:"George", grade:5, school:"MathHighSchool"}, 
    {name:"John", grade:4, school:"MathHighSchool"}, 
    {name:"Paul", grade:3, school:"MathHighSchool"}, 
    {name:"Ringo", grade:5, school:"MathHighSchool"}, 
    {name:"Johnny", grade:2, school:"MathHighSchool"}, 
    {name:"Joshua", grade:7, school:"MathHighSchool"}, 
]) 

假設你只想計數,這裏有一個例子聚合(與MongoDB的2.4.8測試):

db.people.aggregate(
    { $match: { 
     school : 'MathHighSchool' 
    }}, 
    { $group: { 
     _id: "$school", 

     // Add up matches less than grade 3 
     low: { $sum: { $cond: [ {$lt: ["$grade", 3] }, 1, 0] }}, 

     // Add up matches between 3 and 5 (inclusive) 
     medium: { $sum: { $cond:[ 
      { $and: [ {$gte: ["$grade", 3]}, {$lte: ["$grade", 5]} ] }, 1, 0] 
     }}, 

     // Add up matches greater than grade 5 
     high: { $sum: { $cond: [ {$gt: ["$grade", 5] }, 1, 0] }}, 

    }} 
) 

結果:

{ 
    "result" : [ 
     { 
      "_id" : "MathHighSchool", 
      "low" : 1, 
      "medium" : 4, 
      "high" : 1 
     } 
    ], 
    "ok" : 1 
} 
+1

老兄,你太棒了! – user3108836