我正在尝试在 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 ofage
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/