【发布时间】:2018-04-04 21:19:21
【问题描述】:
我的发票型号如下
{
...
"itemDetails": [
{
"item": "593a1a01bbb00000043d9a4c",
"purchasingPrice": 100,
"sellingPrice": 150,
"qty": 200,
"_id": "59c39c2a5149560004173a05",
"discount": 0
}
],
"payments": [],
...
}
Item 详细信息 Item 是一个引用 Item 集合的对象 Id。
我想按项目进行销售,所以我设法按照以下方式解决了问题
Invoice.aggregate([
{
"$unwind": "$itemDetails"
}, {
"$group": {
"_id": "$itemDetails.item",
"qty": {
"$sum": "$itemDetails.qty"
},
"value": {
"$sum": {
"$multiply": [
"$itemDetails.qty", {
"$subtract": ["$itemDetails.sellingPrice", "$itemDetails.discount"]
}
]
}
},
"avarageSellingPrice": {
"$avg": {
"$subtract": ["$itemDetails.sellingPrice", "$itemDetails.discount"]
}
}
}
}
]).then(salesFigures => {
res.status(200).json(salesFigures);
});
这会产生以下结果。
[
{
"_id": "59c89c6d68dffc0004f42a86",
"qty": 50,
"value": 1250,
"avarageSellingPrice": 25
},
{
"_id": "593a4bbfbbb00000043d9a54",
"qty": 320,
"value": 48000,
"avarageSellingPrice": 150
}
]
我需要从项目集合中获取项目名称的结果,例如
[
{
"_id": "59c89c6d68dffc0004f42a86",
"itemName": "Item one",
"qty": 50,
"value": 1250,
"avarageSellingPrice": 25
},
{
"_id": "593a4bbfbbb00000043d9a54",
"itemName": "Item Two",
"qty": 320,
"value": 48000,
"avarageSellingPrice": 150
}
]
我想在分组前使用查找但没有用。
Invoice Collection 中的示例文档
{
"_id": {
"$oid": "59c39c2a5149560004173a04"
},
"customer": {
"$oid": "5935013832f9fc0004fa9a16"
},
"order": {
"$oid": "59c1df8393cbba0004a0e956"
},
"employee": {
"$oid": "592d0a6238880f0004637e84"
},
"status": "PENDING",
"deliveryStatus": "PROCESSING",
"created": {
"$date": "2017-09-21T11:02:02.675Z"
},
"discount": 0,
"payments": [],
"itemDetails": [
{
"item": {
"$oid": "593a1a01bbb00000043d9a4c"
},
"purchasingPrice": 100,
"sellingPrice": 150,
"qty": 200,
"_id": {
"$oid": "59c39c2a5149560004173a05"
},
"discount": 0
}
],
"__v": 0
}
物品文件如下
{
"_id": {
"$oid": "593a1a01bbb00000043d9a4c"
},
"itemCode": 1213,
"itemName": "KIT KAT",
"status": "active",
"created": {
"$date": "2017-06-09T03:46:09.445Z"
},
"__v": 0,
"updated": {
"$date": "2017-06-21T07:46:31.232Z"
},
"purchasingPrice": 100,
"retailPrice": 140,
"sellingPrice": 150
}
【问题讨论】:
-
从您的发票和项目集合中发布一份完整的文档
-
@ClementAmarnath 更新了他们的问题
-
$lookup“之后”$group也是如此。问题是什么?"localField"和"foreignField"都将是_id?或者您是否尝试引用"item"并且当您将其用作分组键时没有计算出该值现在在_id中?
标签: node.js mongodb mongoose aggregation-framework