mongodb嵌套数组元素$ lookup

时间:2018-04-25 17:07:04

标签: mongodb aggregation-framework

我有两个集合,ordersproducts。我想加入所有order.items[]products集合,为items[]

添加更多字段

样本数据:
订单
[{ _id: 1, items: [ { product_id: 1, price: 1.99, qty: 2 }, { product_id: 2, price: 3.99, qty: 5 } ]}]
产品
[{ _id: 1, name: "Product 1" }, { _id: 2, name: "Product 2 }]

预期产量:
[{ _id: 1, items: [ { product_id: 1, name: "Product 1", price: 1.99, qty: 2 }, { product_id: 2, name: "Product 2",, price: 3.99, qty: 5 } ]}]

我尝试使用$ lookup和pipeline(mongodb 3.6)并且没有获取名称值,甚至匹配也无效。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

此查询将对您有所帮助,对不起,如果我没有使用v3.6。

glue

我将解释它们分为4个阶段:

  1. $ unwind将为数组中的每个元素创建一个对象。
  2. $ lookup会找到正确的产品,请记住Product._id应该是唯一的。
  3. $ project将格式化我的文档和items.name我正在查找查找语句的第一个元素。
  4. $ group将使用_id进行分组并将每个项目推送到新阵列。
  5. 我很确定有更清晰,更简单的方法来写这个,但这应该没有问题。