首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >条件$lookup in MongoDB?

条件$lookup in MongoDB?
EN

Stack Overflow用户
提问于 2018-12-10 17:58:09
回答 1查看 14K关注 0票数 8

我在MongoDB 3.6中有两个集合:

代码语言:javascript
复制
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聚合阶段查询用户并连接他角色中的所有数据:

代码语言:javascript
复制
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,以获得这两个集合的笛卡尔积:

代码语言:javascript
复制
db.users.aggregate([{
  "$match": { "name": "Sarah" }
},{
  "$lookup": {
    "from": "roles",
    "pipeline": [],
    "as": "roles"
  }
}]);

有什么方法可以同时拥有这两种情况吗?有条件表达式的吗?

在SQL数据库中,我只需将条件包含在联接中:

代码语言:javascript
复制
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;
--                                          ^^^^^^^^^^^^^^^^^^^^^
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-10 18:11:39

您可以使用下面的聚合

$expr允许在其中使用聚合运算符。因此,您可以很容易地对拥有$cond的用户和没有使用allowedRoles的用户使用allowedRoles聚合。

代码语言:javascript
复制
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"
  }}
])
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53711144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档