У меня есть две коллекции. Образец коллекции product выглядит следующим образом:
{
"_id": "5da3e8e90ddb8a7bb9b404d1",
"updatedAt": "2020-01-07T09:20:02.170Z",
"createdAt": "2019-10-14T03:18:01.421Z",
"brief": {
"category": ",Groceries,Chocolate",
"images": [ "m & m chocolate peanut 45g.jpg" ],
"stock": 10,
"cost": 1.05,
"price": 1.75,
"name": "M&M's Chocolate Peanut",
"code": "SHFP01-019"
}
}
И образец коллекции Order приводится ниже:
{
"_id" : ObjectId("5e26558fc63ab131c518b588"),
"updatedAt" : ISODate("2020-01-21T08:46:32.734Z"),
"createdAt" : ISODate("2020-01-21T01:36:15.817Z"),
"__v" : 0,
"buyer_id" : ObjectId("5dd214a18c34403071166ebd"),
"OrderNo" : "ORD-210",
"products" : [
{
"variants" : [
{
"order_qty" : 1
}
],
"product" : {
"_id" : ObjectId("5d8197f30ddb8a7bb9b401d4"),
"brief" : {
"category" : ",Drinks,Beverages",
"stock" : 10,
"price" : 10.5,
"name" : "Yeo's Sugar Cane ",
"code" : "YEO113",
"images" : [
"Yeo's Sugar Cane 24x250ml.jpg"
],
}
},
},
{
"variants" : [
{
"order_qty" : 1
}
],
"product" : {
"_id" : ObjectId("5d819a760ddb8a7bb9b401e0"),
"brief" : {
"category" : ",Drinks,Beverages",
"stock" : 9,
"price" : 10.5,
"name" : "Yeo's Chrysanthemum Luo Han Guo Tea",
"code" : "YEO118",
"images" : [
"Yeo's Chrysanthemum Luo Han Guo 24x250ml.jpg"
],
}
},
},
{
"variants" : [
{
"order_qty" : 1
}
],
"product" : {
"_id" : ObjectId("5d81991d0ddb8a7bb9b401d8"),
"brief" : {
"category" : ",Drinks,Beverages",
"stock" : 10,
"price" : 10.5,
"name" : "Yeo's Snow Pear",
"code" : "YEO115",
"images" : [
"Yeo's Snow Pear 24x250ml.jpg"
],
}
},
}
],
"commission_status" : "Approved",
"status" : "Paid"
}
The задача состоит в том, чтобы выяснить заказы конкретного покупателя и рассчитать общую заработанную прибыль (прибыль рассчитывается по формуле: сумма (product_cost* order_quantity)
- сумма (product_price * order_quantity)
.
Я использовал эту функцию, но получил неправильный результат .
const buyer = await models.Order.aggregate([
{
$match: {buyer_id:req.body.buyer}
},
{
"$lookup": {
from: "products",
localField: "products.product._id",
foreignField: "_id",
as: "product_cost"
}
},
{ $unwind: "$total" },
{ $unwind: { path: "$product_cost", preserveNullAndEmptyArrays: true }},
{ $unwind: "$products" },
{ $unwind: "$products.variants" },
{
"$group": {
_id: "$buyer_id",
amount: {
$sum: {
$cond: [
{ $eq: ["$product_cost._id", "$products.product._id"] },
{
$multiply: [
"$products.product.brief.price",
"$products.variants.order_qty"
]
},
0
]
}
},
totalcost: {
$sum: {
$cond: [
{ $eq: ["$product_cost._id", "$products.product._id"] },
{
$multiply: [
"$product_cost.brief.cost",
"$products.variants.order_qty"
]
},
0
]
}
}
}
},
{
"$project": {
profit: {
$subtract: ["$amount", "$totalcost"]
}
}
},
{
"$match": {
profit: { $gt: 0 }
}
}
]);