簡體   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