【发布时间】:2022-11-11 03:14:02
【问题描述】:
我有一个电子商务服务器,其中有一个products 和一个orders 集合。
任何product 文档都包含一个唯一的productId,例如prod_123。
每个order 文档都包含一个lineItems(数组)字段,该字段返回所购买产品的productIds 以及相应的quantity 购买例如
[{ productId: 'prod_123', quantity: 2 }, { productId: 'prod_234', quantity: 7 }, ...]
当我的客户获取他们的订单时,我想用products 集合中的匹配产品文档填充每个lineItems 元素的productId。
我已经编写了一个 mongoDB 聚合管道来实现这一点,到目前为止就是这样:
const orderPipeline = [
{
$match: { customerId: 'the customer's ID' },
},
{
$lookup: {
from: 'products',
let: { productIds: '$lineItems.productId' },
pipeline: [
{ $match: { $expr: { $in: ['$productId', '$$productIds'] } } },
//*** somehow, need to add in corresponding `lineItem.quantity` here
],
as: 'products',
},
},
{ $unset: ['lineItems'] },
];
但是,如您所见,虽然连接正在进行,但在删除 lineItems 之前,我无法弄清楚如何将匹配产品的 quantity 添加到连接的 product 中。
如何将对应的quantity 添加到对应的匹配product 中?
【问题讨论】:
-
products中的文档是否基于productId是唯一的?lineItems中是否会出现在products中没有相应条目的产品?换句话说,这将是数组中的条目和另一个集合中的文档之间的1:1匹配吗? -
是的,
products中的文档基于其productId是唯一的。不,每个lineItem都会有一个匹配的product
标签: mongodb mongoose aggregation-framework