mongodb 使用多分支判断 switch...case...then
mongodb switch多分支判断的结构如下
{
"$switch": {
"branches": [
{
"case": {
"<判断条件>"
},
"then": ""
},
{
"case": {
"<判断条件>"
},
"then": ""
},
],
"default": "默认值"
}
}
mongodb switch多分支判断示例
// 构造测试数据
db.col00.insertMany([
{"name": "doc01", "age": 10},
{"name": "doc02", "age": 11},
{"name": "doc03", "age": 12},
{"name": "doc03", "age": 20},
{"name": "doc04", "age": 21},
{"name": "doc05", "age": 22},
{"name": "doc07", "age": 30},
{"name": "doc08", "age": 31},
{"name": "doc09", "age": 32}
]);
// 使用场景:针对测试数据,要实现对年龄(age)按区间进行分组聚合
// 注意点:$$ROOT表示文档自身
db.col00.aggregate([
{
"$project": {
"self": "$$ROOT",
"ageKey": {
"$switch": {
"branches": [
{
"case": {
"$lt": ["$age", 20]
},
"then": "0-20岁"
},
{
"case": {
"$and": [{
"$gte": ["$age", 20]
}, {
"$lt": ["$age", 30]
}]
},
"then": "20-30岁"
}
],
"default": "30岁以上"
}
}
}
},
{
"$group": {
"_id": "$ageKey",
"count": {
"$sum": 1
},
"docs": {
"$push": "$self"
}
}
}
])
mongodb switch多分支判断示例执行结果