mongodb - 具有多个条件的聚合 Switch Case 语法

标签 mongodb switch-statement mongodb-query aggregation-framework

我正在尝试在 Mongo 中执行一个简单的 switch case,但不断收到语法错误消息

db.users.aggregate([
  { $project: {
    "age": 1,
    "Age Group":{
      $switch:{
        branches:[
          {
            case: {$lte:[{"age": "18"}]},
                    then: "Minor"
          },
          {
            case: {$gt:[{"age": "18"}]},
                  {$lte:[{"age": "30"}]},
            then: "Young Adult"
          }
        ],
        default: "No Age Group"
      }
    }
  }}        
])

有人可以帮忙吗?

最佳答案

如果您确实拥有 MongoDB 3.2,则需要 $and对于多个条件:

db.users.aggregate([
  { "$project": {
    "age": 1,
    "Age Group": {
      "$switch": {
        "branches": [
          {
            "case": { "$lte": ["$age", "18"] },
            "then": "Minor"
          },
          // This one <----
          {
            "case": { 
              "$and": [
                { "$gt": ["$age", "18"] },
                { "$lte": ["$age", "30"] }
              ]
            },
            "then": "Young Adult"
          }
        ],
        "default": "No Age Group"
      }
    }
  }}        
])

事实上,分支实际工作的方式不需要两个条件,因为“第一个分支”会短路以下分支:

db.users.aggregate([
  { "$project": {
    "age": 1,
    "Age Group": {
      "$switch": {
        "branches": [
          {
            "case": { "$lte": ["$age", "18"] },
            "then": "Minor"
          },
          // Just needs the $lte condition
          {
            "case": { "$lte": ["$age", "30"] },
            "then": "Young Adult"
          }
        ],
        "default": "No Age Group"
      }
    }
  }}        
])

最重要的是$gt$lte逻辑运算符将“数组”作为参数,而不是您尝试使用它们时的“对象”。这与“查询”运算符形式不同。

Note: you also need to denote "field values" with $, otherwise it's just a "string". And of course the values of age are also strings, so "9" is not actually "less than" "18". You probably should fix your data to store those as numeric values instead.

如果您实际上没有 MongoDB 3.2,那么实际上总是可以通过 $cond 来实现,但语法稍微长一点:

db.users.aggregate([
  { "$project": {
    "age": 1,
    "Age Group": {
      "$cond": {
        "if": { "$lte": ["$age", "18" ] },
        "then": "Minor",
        "else": {
          "if": { "$lte": ["$age", "30"] },
          "then": "Young Adult",
          "else": "No Age Group"
        }
      }
    }
  }}
])

这样“嵌套”的形式$cond基本上就是$switch以不同的语法形式执行,没有“嵌套”。但是$cond自从聚合框架出现以来,您就一直可以这样做。

关于mongodb - 具有多个条件的聚合 Switch Case 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47106413/

相关文章:

java - Java中如何压缩switch结构?

java - 案例未达到正确的数字/程序未正确读取时钟

python - 查询嵌入列表中的数组

mongodb - 如果它是一个数组,如何连接字符串数组字段以显示为一个字符串

asynchronous - async nodejs查询和处理结果

c - 是否可以在 C 开关/案例中使用正则表达式作为案例

javascript - Node.js 和 MongoDB 无法规范化查询

javascript - 查询子文档 MongoDB Node.JS

Mongodb Atlas 图表 - 在不同列中显示分组计数

mongodb - .NET 驱动程序与 LINQ : NotSupportedException: $project or $group