I have the following collections in mydb database:
purchases: it contains documents in the following format:
{ _id: <ObjectId>, name: <String>, //customer name purchasedItems: <Array> 0: < Object > i_name: <String> // item name qntity: <Int> // other objects in the array }
sales: it contains documents in the following format:
{ _id: <ObjectId>, i_name: <String>, qntity: <Int> cost: <Int> }
I'd like to output a new collection that contains the following documents:
{
_id: <ObjectId>,
name: <String>,
cost: <Int>
}
Where name is the name of the customer in the purchases collection and cost is the cost of ALL the items that he purchased.
Formally, each item's cost is defined as:
purchases.purchasedItems.qntity/sales.qntity) * sales.cost
WHERE purchases.purchasedItems.i_name=sales.i_name
and cost in the output collection is the sum of all the items' cost.
I've tried the following but it doesn't work:
db.purchases.aggregate([
{$unwind: "$purchasedItems"},
{$lookup:
{from:"sales",
localField:"purchasedItems.i_name",
foreignField:"i_name",
as: "n_cost"}
},
{
$group:{
_id: "$_id",
name: "$name",
cost: {$sum: {multiply:[{$divide:["$n_cost.qntity","$qntity"]},"$n_cost.cost"]}}
}
},
{$out: "results"}
])
I'd appreciate any help with what I did wrong and what's the correct way to do it.