MongoDB aggregation pipeline

孤街浪徒 提交于 2019-12-08 11:39:31

问题


I have this type of documents:

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

and many more examples. I need a query that finds all people who: study in the MathHighSchool (so we have db.people.aggregate({$match:{school:"MathHighSchool"}},....)

and then group them by their grades, as it shows the number of people with grade <3 number of people with grade between 3 and 5 and number of people with grade > 5. Any ideas?


回答1:


In order to conditionally sum matches in your $group pipeline step, you need to use the $cond operator.

Test data set up:

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"},
])

Assuming you just want the counts, here is an example aggregation (tested with 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:

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


来源:https://stackoverflow.com/questions/20620879/mongodb-aggregation-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!