mongodb - MongoDB中的条件$查找?
问题描述
我在 MongoDB 3.6 中有两个集合:
users: [
{name: "John", allowedRoles: [1, 2, 3]},
{name: "Charles", allowedRoles: [1]},
{name: "Sarah", isAdmin: true}
]
roles: [
{_id: 1, name: "Foo", description: "This role allows to foo the blargs"},
{_id: 2, name: "Bar", description: "..."},
{_id: 3, name: "Doh", descripcion: "..."}
]
我对 MongoDB 很陌生;我刚刚弄清楚如何使用聚合阶段查询用户并加入他角色中的所有数据:$lookup
db.users.aggregate([{
"$match": { "name": "John" } // Or without this $match part, to get all users
},{ //
"$lookup": {
"from": "roles",
"localField": "allowedRoles",
"foreignField": "_id",
"as": "roles"
}
}]);
它适用于我的普通用户,他们有一系列允许的角色 ID。我也有管理员用户,他们可以访问所有现有角色,但没有allowedRoles
数组(维护将是一个负担,因为会频繁创建新角色)。因此,我没有指定连接字段,而是$lookup
使用空管道来获取两个集合的笛卡尔积:
db.users.aggregate([{
"$match": { "name": "Sarah" }
},{
"$lookup": {
"from": "roles",
"pipeline": [],
"as": "roles"
}
}]);
有没有办法通过一个查询同时拥有两者?用条件表达式还是什么?
在 SQL 数据库中,我只需在联接中包含条件:
select users.*, roles.*
from users
left join users_x_roles inter on users.id = inter.user_id
left join roles on inter.role_id = roles.id or users.is_admin = 1;
-- ^^^^^^^^^^^^^^^^^^^^^
解决方案
您可以使用以下聚合
$expr
允许您在其中使用聚合运算符。因此,您可以轻松地$cond
为拥有allowedRoles
和未拥有的用户使用聚合
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"
}}
])
推荐阅读
- flutter - Dart - 无法从连接流中捕获异常
- xamarin.forms - 构建 xamarin.forms ios 项目后 msbuild 挂起,语法错误
- python - Numpy中没有for循环的两个数组之间的元素比较
- sql - 如何合并到一行中的多个结果
- sql - 如何将行插入到具有自动递增的外键的表中,而无需对父表进行多次查询
- r - R使用带有循环的变异进行变量比较
- api - 有什么方法可以使用 Azure DevOps Rest API 针对任何/多个事件类型创建订阅?
- php - Yii2 - wrong order of loaded CSS - extension's CSS breaks the layout
- python-3.x - merging multiple columns into one column
- javascript - 单击按钮 1 周后不显示横幅?