mongodb 使用條件判斷 if...then...else...
mongodb if判斷的結(jié)構(gòu)如下
{
"$cond": {
"if": {
"<判斷條件>"
},
"then": "",
"else": {
// 嵌套查詢
"$cond": {}
}
}
}
mongodb if判斷示例
// 構(gòu)造測(cè)試數(shù)據(jù)
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}
]);
// 使用場(chǎng)景:針對(duì)測(cè)試數(shù)據(jù),要實(shí)現(xiàn)對(duì)年齡(age)按區(qū)間進(jìn)行分組聚合
// 注意點(diǎn):$$ROOT表示文檔自身
db.col00.aggregate([
{
"$project": {
"self": "$$ROOT",
"ageKey": {
"$cond": {
"if": {
"$lt": [
"$age",
20
]
},
"then": "0~20歲",
"else": {
"$cond": {
"if": {
"$and": [
{
"$gte": ["$age", 20]
},
{
"$lt": ["$age", 30]
}
]
},
"then": "20~30歲",
"else": "30歲以上"
}
}
}
}
}
},
{
"$group": {
"_id": "$ageKey",
"count": {
"$sum": 1
},
"docs": {
"$push": "$self"
}
}
}
])
mongodb if判斷示例 執(zhí)行結(jié)果如下
示例執(zhí)行結(jié)果