繁体   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