MongoDB 中的条件 $lookup?

AJP*_*rez 6 mongodb mongodb-query aggregation-framework

我在 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: "..."}
]
Run Code Online (Sandbox Code Playgroud)

我对 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"
  }
}]);
Run Code Online (Sandbox Code Playgroud)

它适用于我的普通用户,他们拥有一系列允许的角色 ID。我还有管理员用户,它们可以访问所有现有角色,但没有allowedRoles数组(维护起来会很麻烦,因为会经常创建新角色)。因此,我没有指定连接字段,而是$lookup使用一个空管道来获取两个集合的笛卡尔积:

db.users.aggregate([{
  "$match": { "name": "Sarah" }
},{
  "$lookup": {
    "from": "roles",
    "pipeline": [],
    "as": "roles"
  }
}]);
Run Code Online (Sandbox Code Playgroud)

有没有办法通过一个查询同时拥有两者?用条件表达式什么的?

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

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: "..."}
]
Run Code Online (Sandbox Code Playgroud)

Ash*_*shh 9

您可以使用以下聚合

$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"
  }}
])
Run Code Online (Sandbox Code Playgroud)

  • 嗯...看看那个语法,我不会把它描述为“简单”:),但它工作得很好。谢谢!! (9认同)