簡體   English   中英

如何在 mongodb 中使用 $lookup 加入三個(多個)集合?

[英]How to join three (multipe) collections with $lookup in mongodb?

如何在 mongodb 中使用 $lookup 加入三個(多個)集合?

嗨,我希望加入來自三個集合的數據

用戶集合:

[
{
_id:0,
name:"abc",
phone:999999999
},
{
_id:1,
name:"xyz",
phone:888888888
},
]

產品集合:

[
{
_id:"p01",
name:"product-name",
price:1200
},
{
_id:"p02",
name:"product-name1",
price:100
}
]

產品評論集合:

[
{
_id:"pr0",
userId:0,
productId:"p01",
star:4
},
{
_id:"pr1",
userId:1,
productId:"p01",
star:3
}
]

mongodb查詢:

product.aggregate([
      {
        $lookup: {
          from: "productreviews",
          localField: "_id",
          foreignField: "productId",
          as: "review",
        },
        
      },
      {
        $lookup: {
          from: "users",
          localField: "review.userId",
          foreignField: "_id",
          as: "review.userInfo",
        },
        
      },
    ])

我無法獲得我需要的輸出。 我怎樣才能得到以下輸出:

{
  product: [
    {
      _id: "p01",
      name: "product-name",
      price: 1200,
      review: [
        {
          _id: "pr0",
          userId: 0,
          productId: "p01",
          star: 4,
          "userInfo": {
            name: "abc",
            phone: 999999999
          }
        },
        {
          _id: "pr1",
          userId: 1,
          productId: "p01",
          star: 3,
          "userInfo": {
            "name": "xyz",
            "phone": 888888888,
          }
        },
      ]
    },
    {
      _id: "p02",
      name: "product-name1",
      price: 100,
    },
  ]
}

任何幫助表示贊賞! 謝謝你...

db.product.aggregate([
  {
    $lookup: {
      from: "review",
      localField: "_id",
      foreignField: "productId",
      as: "review",
      
    },
    
  },
  {
    $lookup: {
      from: "users",
      localField: "review.userId", //See here
      foreignField: "_id",
      as: "review.userInfo",
      
    },
    
  },
  
])

本地字段名稱是第二次查找中的 userId。

操場

編輯:

為了保留評論也

添加一個放松階段

db.product.aggregate([
  {
    $lookup: {
      from: "review",
      localField: "_id",
      foreignField: "productId",
      as: "review",
      
    },
    
  },
  {
    "$unwind": "$review"
  },
  {
    $lookup: {
      from: "users",
      localField: "review.userId",
      foreignField: "_id",
      as: "review.userInfo",
      
    },
    
  },
  
])

更新

要將文檔保留在不匹配的位置,請在展開階段保留空數組,如下所示

  {
    $unwind: {
      path: "$review",
      "preserveNullAndEmptyArrays": true
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM