如何按月、周和天进行聚合-MongoDB



我收集了门票,我需要获得当天、周和月售出的门票数量。以下是的结构

{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 100,
"createdAt": "2021-11-08T08:34:39.697+00:00"
},
{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 101,
"createdAt": "2021-11-07T08:34:39.697+00:00"
},
{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 102,
"createdAt": "2021-11-06T08:34:39.697+00:00"
},
{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 103,
"createdAt": "2021-11-05T08:34:39.697+00:00"
},
{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 104,
"createdAt": "2021-11-04T08:34:39.697+00:00"
},
{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 105,
"createdAt": "2021-11-03T08:34:39.697+00:00"
},
{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 106,
"createdAt": "2021-11-02T08:34:39.697+00:00"
},
{
"_id": "9917aed79fcc274bdefgj",
"ticketId": 107,
"createdAt": "2021-11-01T08:34:39.697+00:00"
}

我是MongoDB的新手,我尝试使用project或match导出当天、周或月,但我没有成功,因此无法分享我的大部分工作。感谢的任何帮助

更新:
查询11月8日时的预期输出
日期:1
周:1
月:8

输出说明:
日:1-给定日期售出的门票数量
周:1-给定周售出的门票数目(从周一开始,仅售出1张门票(
月:8-给定月售出的门票数,售出8张门票

查询

  • 将您想要的日期放在第一集中,如果您想要当前日期,请保留具有当前日期的$$NOW系统变量
  • 年/月/周/日的4倍相同代码
  • 此处在组之前进行筛选,使其具有与当前日期$$NOW日期相同的年、月、周或天

*我使用了$isoWeek一周,从周一开始$week一周从周日开始,你可以更改它们

PlayMongo

aggregate(
[{"$set": {"date": "$$NOW"}},
{"$facet": 
{"year": 
[{"$match": 
{"$expr": {"$eq": [{"$year": "$date"}, {"$year": "$createdAt"}]}}},
{"$group": {"_id": null, "count": {"$sum": 1}}},
{"$unset": ["_id"]}],
"month": 
[{"$match": 
{"$expr": 
{"$and": 
[{"$eq": [{"$year": "$date"}, {"$year": "$createdAt"}]},
{"$eq": [{"$month": "$date"}, {"$month": "$createdAt"}]}]}}},
{"$group": {"_id": null, "count": {"$sum": 1}}},
{"$unset": ["_id"]}],
"week": 
[{"$match": 
{"$expr": 
{"$and": 
[{"$eq": [{"$year": "$date"}, {"$year": "$createdAt"}]},
{"$eq": [{"$isoWeek": "$date"}, {"$isoWeek": "$createdAt"}]}]}}},
{"$group": {"_id": null, "count": {"$sum": 1}}},
{"$unset": ["_id"]}],
"day": 
[{"$match": 
{"$expr": 
{"$and": 
[{"$eq": [{"$year": "$date"}, {"$year": "$createdAt"}]},
{"$eq": 
[{"$dayOfYear": "$date"}, {"$dayOfYear": "$createdAt"}]}]}}},
{"$group": {"_id": null, "count": {"$sum": 1}}},
{"$unset": ["_id"]}]}},
{"$set": 
{"year": 
{"$cond": 
[{"$eq": ["$year", []]}, 0, {"$arrayElemAt": ["$year.count", 0]}]},
"month": 
{"$cond": 
[{"$eq": ["$month", []]}, 0, {"$arrayElemAt": ["$month.count", 0]}]},
"week": 
{"$cond": 
[{"$eq": ["$week", []]}, 0, {"$arrayElemAt": ["$week.count", 0]}]},
"day": 
{"$cond": 
[{"$eq": ["$day", []]}, 0, {"$arrayElemAt": ["$day.count", 0]}]}}}])

结果
(对于"日期"11月9日,我得到的数据(

[
{
"day": 1,
"month": 8,
"week": 1,
"year": 8
}
]

此处测试

db.collection.aggregate([
{
"$project": {
"createdAtWeek": {
"$week": "$createdAt"
},
"createdAtMonth": {
"$month": "$createdAt"
},
"createdAtDay": {
"$dayOfMonth": "$createdAt"
}
}
},
{
"$group": {
"_id": {
createdAtWeek: "$createdAtWeek",
createdAtMonth: "$createdAtMonth",
createdAtDay: "$createdAtDay"
},
count: {
$sum: 1
}
}
}
])

相关内容

  • 没有找到相关文章

最新更新