我有这个orderdetails
型号的
const model = new Schema(
{
district: { type: String },
category: String,
producer: String,
variety: String,
qty: String,
price: String,
subtotal: String,
},
{ timestamps: true }
);
我想在variety
之前拿到月度销售报告。首先我过滤variety
,然后按月份分组,计算出qty
的总和
这是我的查询
const monthly = await OrderDetails.aggregate([
{
$match: {
variety,
},
},
{
$group: {
_id: {
month: { $month: "$createdAt" },
qty: { $sum: { $toInt: "$qty" } },
},
},
},
{ $sort: { _id: 1 } },
{
$project: {
qty: "$_id.qty",
Month: {
$arrayElemAt: [
[
"",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
"$_id.month",
],
},
},
},
]);
但是输出是这样的
此查询的输出是此
[
{ _id: { month: 4, qty: 1 }, qty: 1, Month: 'Apr' },
{ _id: { month: 4, qty: 5 }, qty: 5, Month: 'Apr' }
]
但预期的输出是一个记录,总数量是6,就像这个
[
{ _id: { month: 4, qty: 6 }, qty: 6, Month: 'Apr' },
]
我的查询出了什么问题?
由于数量用于累加器,请从更改$group
{
$group: {
_id: {
month: { $month: "$createdAt" },
qty: { $sum: { $toInt: "$qty" } }
}
}
}
至
{
$group: {
_id: { month: { $month: "$createdAt" } },
qty: { $sum: { $toInt: "$qty" } }
}
}
mongoplayground