如何解决如何在mongodb集合中不存在的月份中返回0
var start = new Date();
start.setHours(0,0);
start.setMonth(start.getMonth() - 12);
var end = new Date();
end.setHours(23,59,999);
Orders.aggregate([{
$match: {
'created_at': {
$gte: start,$lte: end
}
}
},{
"$group": {
"_id": {
"year": { "$year": "$created_at" },"month": { "$month": "$created_at" }
},"total_sales": { "$sum": "$total" }
},},{
$sort: { '_id.year': 1,'_id.month': 1,}
},{
$addFields: {
'_id.month': {
$let: {
vars: {
monthsInString: [,'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']
},in: {
$arrayElemAt: ['$$monthsInString','$_id.month']
}
}
}
}
},])
上面的查询返回:
[
{ _id: { year: 2019,month: 'Dec' },total_sales: 1800 },{ _id: { year: 2020,month: 'Apr' },total_sales: 5700 },month: 'May' },total_sales: 6630 },month: 'Jun' },total_sales: 690 },month: 'Jul' },total_sales: 1600 },month: 'Aug' },total_sales: 13430 }
]
如果该月没有文档,该月该如何更改为该月的total_sales返回0。例如,一月份没有订单。我希望它在该月和其他没有文档的月中返回total_sales=0
。过去12个月或6个月。
示例文档:
_id : 5f3d0c6677d1471d8a8438e1
orderid :"aydc1kehke1aj47l"
user :5f3cf2c61282c415bfd2a432
products :Array
total : 1800
firstName:"ishak"
lastName: "ertem"
created_at:2020-03-21T11:26:30.647+00:00
解决方法
具有以下结构(在$sort
阶段之后):
[
{ _id: { year: 2019,month: 12 },total_sales: 1800 },{ _id: { year: 2020,month: 4 },total_sales: 5700 },month: 5 },total_sales: 6630 },month: 6 },total_sales: 690 },month: 7 },total_sales: 1600 },month: 8 },total_sales: 13430 }
]
您可以使用$range生成一个包含12个整数的列表,可以使用$map每年对其进行迭代,并使用$filter和$arrayElemAt与传入数据进行匹配。另外,$ifNull可用于指定默认值。
db.collection.aggregate([
{
$group: {
_id: "$_id.month",months: { $push: "$$ROOT" }
}
},{
$project: {
months: {
$map: {
input: { $range: [ 1,12 ] },as: "monthIndex",in: {
$ifNull: [
{ $arrayElemAt: [ { $filter: { input: "$months",cond: { $eq: [ "$$this.month","$$monthIndex" ] } } },0 ] },{ _id: { year: "$_id",month: "$$monthIndex" },total_sales: 0 }
]
}
}
}
}
},{
$unwind: "$months"
},{
$replaceRoot: { newRoot: "$months" }
}
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。