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