mongoDB mongoose 按月和总和分组
mongoDB mongoose group by month and total sum
我有这个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' },
]
我的查询有什么问题?
由于 qty 用于累加器,因此将您的 $group
从
更改为
{
$group: {
_id: {
month: { $month: "$createdAt" },
qty: { $sum: { $toInt: "$qty" } }
}
}
}
到
{
$group: {
_id: { month: { $month: "$createdAt" } },
qty: { $sum: { $toInt: "$qty" } }
}
}
我有这个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' },
]
我的查询有什么问题?
由于 qty 用于累加器,因此将您的 $group
从
{
$group: {
_id: {
month: { $month: "$createdAt" },
qty: { $sum: { $toInt: "$qty" } }
}
}
}
到
{
$group: {
_id: { month: { $month: "$createdAt" } },
qty: { $sum: { $toInt: "$qty" } }
}
}