2013-12-16 244 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