【问题标题】:MongoDB aggregation pipelineMongoDB聚合管道
【发布时间】:2013-12-16 21:04:05
【问题描述】:

我有这种类型的文件:

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

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

然后按他们的成绩分组,因为它显示了成绩 5 的人数。有什么想法吗?

【问题讨论】:

  • 嗯,你是什么意思?我已经尝试了 2 个小时左右。
  • {$group:{_id:"$grade", 低:{$lt:3}, 中:{$and:[{lte:5},{gte:3}], 高:{gt:5}}}}) 类似的东西,但不起作用
  • 您的问题基本上与这个 (stackoverflow.com/questions/19967701/…) 相对应,这仍然没有答案...我的第一个猜测是您需要三个不同的查询,然后将结果放在一起。
  • 也许这个 (nrg-media.de/2013/10/…) 帖子也有帮助,还没有深入阅读

标签: mongodb mongodb-query


【解决方案1】:

为了在$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
}

【讨论】:

  • 哥们,你太棒了!
【解决方案2】:

我们也可以在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 2020-09-20
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2018-07-07
    相关资源
    最近更新 更多