我在 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"
}}
])
关于mongodb - MongoDB 中的条件 $ 查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53711144/