我已经收集了机票,我需要在日、周、月卖出多少张票。下面是结构
{
"_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的新手,我试着使用项目或匹配来导出日期、周或月,但是我没有成功,因此无法分享我的大部分工作。感谢你的帮助
更新:
查询08-11月的预期输出
日期:1
周:1
月份:8
对产出的解释:
一天:1-不。在指定日期售出的票
一周:1-不。在给定的一周内售出的票(从星期一开始,只售出一张)。
月份:8-不。在该月份售出的门票中,有8张已售出。
发布于 2021-11-08 20:52:38
查询
$$NOW系统变量。$$NOW日期与当前日期具有相同的年份或月份或周或日。*我使用$isoWeek在星期一开始,$week在星期日开始每周,你可以改变它们
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
}
]发布于 2021-11-08 19:23:02
db.collection.aggregate([
{
"$project": {
"createdAtWeek": {
"$week": "$createdAt"
},
"createdAtMonth": {
"$month": "$createdAt"
},
"createdAtDay": {
"$dayOfMonth": "$createdAt"
}
}
},
{
"$group": {
"_id": {
createdAtWeek: "$createdAtWeek",
createdAtMonth: "$createdAtMonth",
createdAtDay: "$createdAtDay"
},
count: {
$sum: 1
}
}
}
])https://stackoverflow.com/questions/69888707
复制相似问题