我试图弄清楚如何将工作日的名称添加到显示的字段中?到目前为止,它仍然有效,但是仅显示“ Count”和“ Completed At”字段。
它应该显示以下内容:
| Weekday | Count |
–––––––––––––––––––
| Monday | 1 |
| Tuesday | 10 |
| Wedne.. | ... |
这是我的查询:
[
{
"$project": {
"completedAt": "$completedAt",
"status": "$status"
}
},
{
"$match": {
"$and": [
{
"status": {
"$eq": "successful"
}
},
{
"completedAt": {
"$gt": ISODate("2019-01-01")
}
}
]
}
},
{
"$project": {
"_id": "$_id",
"___group": {
"completedAt": {
"$dayOfWeek": "$completedAt"
}
}
}
},
{
"$group": {
"_id": "$___group",
"count": {
"$sum": 1
}
}
},
{
"$sort": {
"_id": 1
}
},
{
"$project": {
"_id": false,
"completedAt": "$_id.completedAt",
"count": true
}
},
{
"$sort": {
"completedAt": 1
}
}
]
答案 0 :(得分:0)
在查询中添加包括$ switch的标签为我解决了该问题。
[
{
"$project": {
"completedAt": "$completedAt",
"status": "$status"
}
},
{
"$match": {
"$and": [
{
"status": {
"$eq": "successful"
}
},
{
"completedAt": {
"$gt": ISODate("2019-01-01")
}
}
]
}
},
{
"$project": {
"_id": "$_id",
"___group": {
"completedAt": {
"$dayOfWeek": "$completedAt"
}
}
}
},
{
"$group": {
"_id": "$___group",
"count": {
"$sum": 1
}
}
},
{
"$sort": {
"_id": 1
}
},
{
"$project": {
"_id": false,
"count": true,
"label": {
"$switch": {
"branches": [
{
"case": { "$eq": ["$_id.completedAt", 1] },
"then": "Sunday"
},
{
"case": { "$eq": ["$_id.completedAt", 2] },
"then": "Monday"
},
{
"case": { "$eq": ["$_id.completedAt", 3] },
"then": "Tuesday"
},
{
"case": { "$eq": ["$_id.completedAt", 4] },
"then": "Wednesday"
},
{
"case": { "$eq": ["$_id.completedAt", 5] },
"then": "Thursday"
},
{
"case": { "$eq": ["$_id.completedAt", 6] },
"then": "Friday"
},
{
"case": { "$eq": ["$_id.completedAt", 7] },
"then": "Saturday"
}
],
"default": "Unknown"
}
}
}
},
{
"$sort": {
"completedAt": 1
}
}
]