【问题标题】:MongoDb join 2 collections by _id and select resultMongoDb 通过 _id 加入 2 个集合并选择结果
【发布时间】:2021-12-22 23:16:51
【问题描述】:

我想从这 2 个集合中选择具有版主角色的用户。

USERS 集合

[
  {
    _id: "701",
    username: "user1",
    roles: [
      "617",
      "618"
    ]
  },
  {
    _id: "702",
    username: "user2",
    roles: [
      "617"
    ]
  },
  {
    _id: "703",
    username: "user3",
    roles: [
      "617",
      "619"
    ]
  },
  {
    _id: "704",
    username: "user4",
    roles: [
      "617",
      "619"
    ]
  }
]

角色集合

[
  {
    _id: "617",
    name: "simpleuser"
  },
  {
    _id: "618",
    name: "admin"
  },
  {
    _id: "619",
    name: "moderator"
  }
]

在 SQL 中会是这样的:

SELECT * FROM USERS
JOIN ROLES ON ROLE_ID = USER_ROLES
WHERE ROLE_NAME = "moderator"

我无法用 mongodb mongoose 弄清楚。请帮帮我。谢谢。

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    您可以将$lookup 与这样的管道一起使用:

    • 首先$lookup使用$in匹配角色id,因为它在一个数组中,$eq比较角色。
    • 这会生成一个名为roles 的字段,它会覆盖现有字段(如果不想覆盖,可以更改名称),然后使用$match 匹配角色不为空的文档(即与角色表一致)。
    db.users.aggregate([
      {
        "$lookup": {
          "from": "roles",
          "let": {"roles": "$roles"},
          "pipeline": [
            {
              "$match": {
                "$expr": {
                  "$and": [
                    {"$in": ["$_id","$$roles"]},
                    {"$eq": ["$name","moderator"]}
                  ]
                }
              }
            }
          ],
          "as": "roles"
        }
      },
      {
        "$match": {
          "roles": {"$ne": [] }
        }
      }
    ])
    

    例如here

    使用猫鼬你可以做到:

    const result = await yourCollection.aggregate(/*the query*/)
    res.status(200).send(result) // or whatever
    

    或者使用回调

    yourCollection.aggregate(/*the query*/).then(result => {res.status(200).send(result)})
    

    另外,你可以使用$projectstage 发送你想要的字段到前端,例如只发送username你可以使用this query

    【讨论】:

    • 这在这个例子中有效,非常感谢。但是如何将结果保存在变量中或发送到前端? res.send(????) 我尝试了 result = 你的代码,然后是 console.log(result),但我得到了一些模型,比如 Aggregate { _pipeline: [ { '$lookup': [Object] }, { '$匹配':[​​对象] }],_model:模型{用户},选项:{}}
    • 更新了!希望能帮助到你。我想你忘记了async/await
    • 谢谢。现在可以了,问题出在另一个集合上。我想使用导出的 mongoose 模型添加到您的代码中,但不需要,只需使用集合名称即可。
    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多