【发布时间】:2020-05-23 14:12:34
【问题描述】:
嘿,我需要按天获取所有 totalPrice 组的总和
我得到了这个结果
但我需要获取一个月的所有休息日,即使它返回 0
我需要解决方案 这是我的代码
Order.aggregate([
{ $project: { yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: '$created' }}, totalPrice:"$totalPrice" }},
{ $group: { _id: "$yearMonthDay", count: { $sum: 1 }, total: {"$sum": "$totalPrice"} }},
{ $sort: { _id: -1 } },
{ $group: { _id: null, stats: { $push: "$$ROOT" }}},
{
$project: {
results: {
$map: {
input:{ $range:[16,31] },
as: 'day',
in: {
$let: {
vars: {
dateIndex: {
"$indexOfArray": ["$stats._id", {$dateToString:{ date:{$dateFromParts:{'year':2020, 'month':5, 'day':"$$day"}}, format:'%Y-%m-%d'}}]
}
},
in: {
$cond: {
if: { $ne: ["$$dateIndex", -1] },
then: { $arrayElemAt: ["$stats", "$$dateIndex"] },
else: { _id: {$dateToString:{ date:{$dateFromParts:{'year':2020, 'month':5, 'day':"$$day"}}, format:'%Y-%m-%d'}, count: 0, total: 0 } }
}
}
}
}
}
}
}
},
{ $unwind: "$results" },
{ $replaceRoot: { newRoot: "$results"}}
]
【问题讨论】:
-
这能回答你的问题吗? Fill missing dates in records
-
我什么都不懂,我认为这不一样我有我需要的 totalprice 变量,即使总价为 0
-
你能发布预期的结果吗?它应该返回什么(
2020-05-16,2020-05-15,2020-05-14,2020-05-13,...)?
标签: mongodb mapreduce mongodb-query aggregation-framework aggregate