Mongodb查询多个集合

时间:2018-07-06 06:55:26

标签: node.js mongodb

我有两个收藏夹

用户

[{
    "id":1,
    "name":"a1",
    "emailAddress":"1@s.com",
},
{
    "id":2,
    "name":"a2",
    "emailAddress":"2@s.com",
},
{
    "id":3,
    "name":"a3",
    "emailAddress":"3@s.com",
}]

组织

[{
    "emailAddress": "1@s.com",
    "name" : "org1"
},
{
    "emailAddress": "2@s.com",,
    "name" : "org1"
},
{
    "emailAddress" : "3@s.com",
    "name" : "org2"
}]

现在,我要像下面这样提取组织 org1 的所有用户

[{
    "id":1, "name":"a1", "emailAddress":"1@s.com","orgName" : "org1"
},
{
    "id":2, "name":"a2", "emailAddress":"2@s.com","orgName" : "org1"
}]

我已经检查了debRef和lookup,但是它们以嵌套形式返回

我该如何实现?

1 个答案:

答案 0 :(得分:2)

您可以使用$lookup$project聚合来简单地实现这一目标

如果您的Mongodb版本为 3.6 及更高版本

db.users.aggregate([
  { "$lookup": {
    "from": Organisation.collection.name,
    "let": { "emaildid": "$emaildid" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$emaildid", "$$emaildid" ] } } }
    ],
    "as": "organisation"
  }},
  { "$unwind": "$organisation" },
  { "$project": {
    { "id": 1, "name": 1, "emailid": 1, "org": "$organisation.org1" }
  }}
])

如果您拥有mongodb版本 3.4 及更低版本

db.users.aggregate([
  { "$lookup": {
    "from": Organisation.collection.name,
    "localField": "emaildid",
    "foreignField": "emaildid",
    "as": "organisation"
  }},
  { "$unwind": "$organisation" },
  { "$project": {
    { "id": 1, "name": 1, "emailid": 1, "org": "$organisation.org1" }
  }}
])

也尝试$replaceRoot

db.Organisation.aggregate([
  { "$match": { "name": "org1" }},
  { "$lookup": {
    "from": Organisation.collection.name,
    "let": { "emailAddress": "$emailAddress", "name": "$name" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$emailAddress", "$$emailAddress" ] } } },
      { "$addFields": { "orgName": "$$name" }}
    ],
    "as": "users"
  }},
  { "$unwind": "$users" },
  { "$replaceRoot": { "newRoot": "$users" } }
])