所以我在下面的 MongoDB 文档中列出了一组对象:
data=[
{
"_id": {
"$oid": "63f5e2449741a13be769ca16"
},
"userId": {
"$oid": "63f5bf0c0dc9b0c36ff32087"
},
"Jumlah": 12600,
"Batch": "9999999",
"Material":"2123100085",
"Expired_Date": "2099-99-99",
"Gedung": "C",
"Zona": "STAGING INBOUND",
"Plant": "K118",
"Transaction_Status": "verified",
"Transaction_Date": "2023-02-22",
"createdAt": 1677058628,
"updatedAt": 1677058628,
"__v": 0,
"From": "INBOUND BONGKAR"
},{
"_id": {
"$oid": "63f5e2449741a13be769ca16"
},
"userId": {
"$oid": "63f5bf0c0dc9b0c36ff32087"
},
"Material":"2123100085",
"Jumlah": 600,
"Batch": "9999999",
"Expired_Date": "2099-99-99",
"Gedung": "C",
"Zona": "STAGING INBOUND",
"Plant": "K118",
"Transaction_Status": "verified",
"Transaction_Date": "2023-02-22",
"createdAt": 1677058628,
"updatedAt": 1677058628,
"__v": 0,
"From": "INBOUND BONGKAR"
},{
"_id": {
"$oid": "63f5e2449741a13be769ca16"
},
"userId": {
"$oid": "63f5bf0c0dc9b0c36ff32087"
},
"Jumlah": 12100,
"Batch": "9999999",
"Material":"2123100085",
"Expired_Date": "2099-99-99",
"Gedung": "C",
"Zona": "STAGING INBOUND",
"Plant": "K118",
"Transaction_Status": "verified",
"Transaction_Date": "2023-02-23",
"createdAt": 1677058628,
"updatedAt": 1677058628,
"__v": 0,
"From": "INBOUND BONGKAR"
}
]
我尝试使用 MongoDB 查询按日期对其进行分组,结果如下:
{
"status": 200,
"message": "Success",
"data": [
{
"_id": "2022400045",
"data": [
{
"x": "2023-02-22",
"y": 20400
},
{
"x": "2023-02-25",
"y": 20000
},
{
"x": "2023-02-25",
"y": 9000
},
{
"x": "2023-02-25",
"y": 4000
},
{
"x": "2023-02-25",
"y": 7000
},
{
"x": "2023-02-25",
"y": 3000
},
{
"x": "2023-02-25",
"y": 3000
}
]
},
]
}
这是我的尝试:
const result = await TransactionIB.aggregate([
{ $match: { Transaction_Date: { $gte: date1, $lte: date2 } } },
{
$group: {
_id: "$Material",
Material_Description: { $first: "$Material_Description" },
data: {
$push: {
x: "$Transaction_Date",
y: { $sum: "$Jumlah" },
},
},
},
},
]);
这是一种优化查询的方法,因此预期值不仅按材料分组,而且按日期分组,预期结果如下,或对此有任何帮助吗?:
"data": [
{
"_id": "2022400045",
"data": [
{
"x": "2023-02-22",
"y": 20400
},
{
"x": "2023-02-25",
"y": 500000
},
]
},
]
需要两级组,
$group
Material
和 Transaction_Date
并在 Jumlah
中得到
y
$group
仅由Material
构建data
数组db.collection.aggregate([
{
$group: {
_id: {
Material: "$Material",
Transaction_Date: "$Transaction_Date"
},
Material_Description: {
$first: "$Material_Description"
},
y: {
$sum: "$Jumlah"
}
}
},
{
$group: {
_id: "$_id.Material",
Material_Description: {
$first: "$Material_Description"
},
data: {
$push: {
x: "$_id.Transaction_Date",
y: "$y"
}
}
}
}
])