如何使用嵌套数组进行mongodb内部联接?

时间:2018-10-14 15:53:40

标签: mongodb typescript multidimensional-array inner-join

仓库模式:

{_id: 1, name: 'A'}
{_id: 2, name: 'B'}
{_id: 3, name: 'C'}

股票模式:

{_id: 11, productId: 1, instock: [{warehouse: 'A', qty: 20}, {warehouse: 'B', qty: 5}, {warehouse: 'C', qty: 8}]
{_id: 12, productId: 2, instock: [{warehouse: 'A', qty: 30}]

我是MongoDB的新手,但是希望每条记录有一行来显示产品在A,B,C仓库中的可用数量:

所需的数组输出:

instock: [
           {_id: 11, productId: 1, warehouse: 'A', qty: 20},
           {_id: 11, productId: 1, warehouse: 'B', qty: 5},
           {_id: 11, productId: 1, warehouse: 'C', qty: 8},
           {_id: 12, productId: 2, warehouse: 'A', qty: 30},
           {_id: 12, productId: 2, warehouse: 'B', qty: 0},
           {_id: 12, productId: 2, warehouse: 'C', qty: 0}
]

我了解了有关$ lookup,$ unwind,$ project的信息,并尝试了如下所示的操作,但没有达到我想要的目标:

    Warehouse.aggregate([
    {
      $lookup:
      {
        from: "stocks",
        pipeline: [ 
          { $project: { _id: 0, instock: {qty: 1, warehouse: 1} }},  
          { $replaceRoot: { newRoot: { newStock : '$instock' } } } 
        ],
        as: "instock"
      }
    } ,
 ]);

嗨,Anothony Winzlet,您的建议部分起作用,例如:

{_id: 12, productId: 2, instock: [{warehouse: 'A', qty: 30}]

从您的解决方案: 结果仅显示仓库A:

[{_id: 12, productId: 2, warehouse: 'A', qty: 30}] 

我是否也可以购买B&C仓库? (如果未定义,默认数量为0)

[{_id: 12, productId: 2, warehouse: 'A', qty: 30},
 {_id: 12, productId: 2, warehouse: 'B', qty: 0},
 {_id: 12, productId: 2, warehouse: 'C', qty: 0}]

不确定上面是否可以实现...谢谢

1 个答案:

答案 0 :(得分:0)

Anthony Winzlet的解决方案:

Warehouse.aggregate([
  { "$unwind": "$instock" },
  { "$replaceRoot": { "newRoot": { "$mergeObjects": ["$$ROOT", "$instock"] } }},
  { "$project": { "instock": 0 } }
])