MongoDB聚合管道

时间:2013-12-16 21:04:06

标签: mongodb mongodb-query

我有这种类型的文件:

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

还有更多例子。 我需要一个查找所有人的查询: 在MathHighSchool学习(所以我们有db.people.aggregate({$match:{school:"MathHighSchool"}},....

然后按成绩对它们进行分组,因为它显示的是成绩<3的人数 3到5年级的人数 和成绩的人数&gt; 5.有什么想法吗?

2 个答案:

答案 0 :(得分: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 :(得分:0)

我们也可以在 mongo 中使用 switch case 来实现这个解决方案,如果条件也是如此,这里有一个实现解决方案的小方法。

查询:

db.people.aggregate([
    {$match:{"school":"MathHighSchool"}},
    {$project:{"school":1,"div": { $switch:
    {
        branches: [
        {
            case: { $lte : ["$grade", 3 ] },
            then: "less than or equal to 3"
        },
        {
            case: { $and : [ { $gt : ["$grade", 3 ] },
            { $lt : [ "$grade", 5 ] } ] },
            then: "between 3 and 5"
        },
        {
            case: { $gte : [ "$grade", 5] },
            then: "greater than or equal to 5"
        }],
    }}}},
    {$group:{"_id":"$div","count":{$sum:1}}}
]);

结果:

{ 
    "_id" : "between 3 and 5", 
    "count" : 1.0
}
{ 
    "_id" : "less than or equal to 3", 
    "count" : 2.0
}
{ 
    "_id" : "greater than or equal to 5", 
    "count" : 3.0
}

请访问此处了解更多详情https://beingcodeexpert.blogspot.com/2021/02/switch-conditional-operator-in-mongodb.html