mongodb - MongoDB 中的条件 $ 查找?

标签 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: "..."}
]

我是 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/

相关文章:

node.js - 使用 MongoDB 的用户分割引擎

ruby-on-rails - Docker rails mongodb NoServerAvailable

Mongodb查询计算每个文档两个日期之间的天数

mongodb - 将字符串日期转换为 MongoDB 中的日期

arrays - Mongo 更新数组内对象的多个字段

c# - 在聚合框架 C# 中使用 Facets

MongoDB - 在 $lookup 之后使用 $group 倒回 $unwind 嵌套数组

node.js - MongoDB/Mongoose 查询 : How to get different sets of data based on a field's value

mongodb - hadoop mongodb连接器构建失败

mongodb - 过滤子文档数组