更新时间:2022-06-08 22:11:13
可以使用下面的聚合
$expr
允许您在其中使用聚合运算符.所以你可以轻松使用 $cond
具有allowedRoles
和没有
$expr
allows you use aggregation operator inside it. So you can easily use $cond
aggregation for the users who has allowedRoles
and who hasn't
db.users.aggregate([
{ "$match": { "name": "Charles" }},
{ "$lookup": {
"from": "roles",
"let": { "ar": "$allowedRoles" },
"pipeline": [
{ "$match": {
"$expr": {
"$cond": [
{ "$eq": [{ "$type": "$$ar" }, "missing"] },
{},
{ "$in": ["$_id", "$$ar"] }
]
}
}}
],
"as": "roles"
}}
])