我被困在一個查詢中,我的情況是
if user id exists then user id
else if user name exists then user name
else if user email exists then user email
else ''
這是我的代碼。
$project: {
..... other fields,
'userDetail': {
$cond: {
if: {
$exists: ['$user.id']
},
then: '$user.id',
else: {
$cond: {
if: {
$exists: ['$user.name']
},
then: '$user.name',
else: {
$cond: {
if: {
$exists: ['$user.email']
},
then: '$user.email',
else: '',
}
},
}
}
}
}
}
因為, $exists 對此不起作用。任何人都可以幫我找到解決這個問題的方法嗎?此外,如果 user.id 為 ''(空字串)且 user.name 為“Marcus”。我希望結果回傳 user.name。
uj5u.com熱心網友回復:
如果我理解正確(并基于您的示例),您可以使用如下查詢:
這里的技巧是使用ifNull而不是$exists.
db.collection.aggregate([
{
"$project": {
"userDetail": {
"$cond": [
{
"$ifNull": [
"$user.id",
false
]
},
// user id exists
"$user.id",
// user id no exists
{
"$cond": [
{
"$ifNull": [
"$user.name",
false
]
},
// user name exists
"$user.name",
// user name no exists
{
"$cond": [
{
"$ifNull": [
"$user.email",
false
]
},
// user email exists
"$user.email",
// user email no exists
""
]
}
]
}
]
}
}
}
])
這里的例子
uj5u.com熱心網友回復:
您可以$ifNull通過檢查嵌套條件來使用嵌套運算子,
{
$project: {
userDetail: {
$ifNull: [
"$user.id",
{
$ifNull: [
"$user.name",
{ $ifNull: ["$user.email", ""] }
]
}
]
}
}
}
操場
uj5u.com熱心網友回復:
詢問
- 如果
id為假或空字串,請嘗試name,否則如果為name假或空字串,請嘗試email,否則"" - false 都是不存在的/null/false
- 這些欄位的型別不是布林值,因此您可以安全地使用這種方式
*如果你真的需要$exist例如你想保留null或false值的例子,你可以使用這個{"$eq":[{"$type":"$user.id"}, "missing"]}
測驗代碼在這里
aggregate(
[{"$set":
{"userInfo":
{"$switch":
{"branches":
[{"case":{"$and":["$user.id", {"$ne":["$user.id", ""]}]},
"then":"$user.id"},
{"case":{"$and":["$user.name", {"$ne":["$user.name", ""]}]},
"then":"$user.name"},
{"case":{"$and":["$user.email", {"$ne":["$user.email", ""]}]},
"then":"$user.email"}],
"default":""}}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430440.html
標籤:mongodb
