Lets say I have two documents in products collection:
{
_id: ObjectId("abc"), name: "Pizza",
attributes: [
{salePrice: 250, size: "Small"},
{salePrice: 300, size: "Medium"},
{salePrice: 350, size: "Large"}
]
},
{
_id: ObjectId("xyz"), name: "Burger",
attributes: [
{salePrice: 100, size: "Regular"},
{salePrice: 150, size: "Large"}
]
}
I have added products to cart so a document in cart collection looks like this:
{
cartProducts: [
{ productId: ObjectId("xyz"), type: "Large", quantity: 5 },
{ productId: ObjectId("abc"), type: "Regular", quantity: 2 },
]
}
I want to retrieve cart details ( all cart items ) with details based on "type" field of cart.cartProducts meet the "size" field of product.attributes. So the output would look like this:
cart items
{
cartDetails: [
{
name: "Pizza", quantity: 5, salePrice: 350, productId: "xyz"
},
{
name: "Burger", quantity: 2, salePrice: 100, productId: "abc"
}
]
}
How can I do that using aggregate. What are the next stages?
Cart.aggregate([
{ $unwind: { path: "$cartProducts" } },
{$lookup:{ from:"products", localField:"cartProducts.productId", foreignField:"_id", as:"products" } },
{ $unwind: { path: "$products", includeArrayIndex: "arrayIndex", preserveNullAndEmptyArrays: true } }
]);