繁体   English   中英

MongoDB查询多个集合

[英]Mongodb query multiple collection

我有两个收藏

用户

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

Organaziation

[{
    "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,但是它们以嵌套形式返回

我该如何实现?

您可以简单地使用$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" } }
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM