首页 > 解决方案 > 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;
--                                          ^^^^^^^^^^^^^^^^^^^^^

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以使用以下聚合

$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"
  }}
])

推荐阅读