1

我想在蒙戈做一個簡單的開關情況,但總是收到語法錯誤信息匯聚交換機案例語法

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

誰能幫助嗎?

回答

1

只要你確實有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" 
     } 
    } 
    }}   
]) 

其實不然,雖然,實際上分支工作,你並不需要兩個條件,因爲「第一支」短的方式-circuits如下分支:

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邏輯運算符,你試圖使用他們採取「陣列」作爲參數,而不是一個「對象」。這與「查詢」操作符表單不同。

注:還需要表示「字段值」與$,否則它只是一個「串」。當然age的值也是字符串,所以"9"實際上並不是「小於」"18"。你可能應該修正你的數據,將它們存儲爲數字值。

如果你實際上並沒有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只要聚合框架一直存在,所以你總是可以做到這一點。