Javascript 显示mongoDB中存储日期的星期
我希望以以下格式显示过去7天内每天的购买量:Javascript 显示mongoDB中存储日期的星期,javascript,node.js,mongodb,express,server,Javascript,Node.js,Mongodb,Express,Server,我希望以以下格式显示过去7天内每天的购买量: { "sunday":30, "monday":20, ... } 数据库上的一次购买如下所示: { _id: 603fcbcc691d8a5ecc320059 productId: "603fc917a569f565687e2626" clientId: "1" totalPrice: 50 date
{
"sunday":30,
"monday":20,
...
}
数据库上的一次购买如下所示:
{
_id: 603fcbcc691d8a5ecc320059
productId: "603fc917a569f565687e2626"
clientId: "1"
totalPrice: 50
date: 2021-03-02T00:00:00.000+00:00 // a date object
}
Purchase.aggregate([
{ "$match": { "date": {$gte: new Date((new Date().getTime() - (7 * 24 * 60 * 60 * 1000))) } } },
{ "$group": {
"_id": { "day": { $substrCP: [ "$date", 0, 10 ] } },
"count": { $sum: 1 }
}},
{ "$sort" : { "_id.day": 1}},
])
我运行此代码并得到:
[
{
"_id": {
"day": "2021-02-28"
},
"count": 30
},
{
"_id": {
"day": "2021-03-01"
},
"count": 20
}
]
这可能会对您有所帮助,但我在mongodb中找不到任何现成的方法,该方法将Sunday的值设为1。这就是为什么要保留switch语句
collection.aggregate([
{ "$match": { "date": { $gte: new Date((new Date().getTime() - (7 * 24 * 60 * 60 * 1000))) } } },
{
"$group": {
"_id": { $dayOfWeek: "$date" },
"count": { $sum: 1 }
}
},
{ "$sort": { "_id": 1 } },
{
$group: {
_id: null,
data: {
$push: {
k: {
$switch: {
branches: [
{
case: { $eq: ["$_id", 1] },
then: "monday"
},
{
case: { $eq: ["$_id", 2] },
then: "tuesday"
},
{
case: { $eq: ["$_id", 3] },
then: "wednesday"
},
{
case: { $eq: ["$_id", 4] },
then: "thursday"
},
{
case: { $eq: ["$_id", 5] },
then: "friday"
},
{
case: { $eq: ["$_id", 6] },
then: "saturday"
},
{
case: { $eq: ["$_id", 7] },
then: "sunday"
}]
}
},
v: "$count"
}
}
}
},
{
$project: {
data: { $arrayToObject: "$data" }
}
}
])
我没有使用switch语句,而是使用以下语句: 在agregate()之前,我使用值初始化了一个数组:
const days = ['','Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
阿格雷戈是这样说的:
Purchase.aggregate([
{ "$match": { "date": { $gte: new Date((new Date().getTime() - (7 * 24 * 60 * 60 * 1000))) } } },
{
"$group": {
"_id": "$date",
"count": { $sum: 1 }
}
},
{ "$sort": { "_id": 1 } },
{
"$project": {
"_id": 0,
"count": 1,
"day": { $arrayElemAt: [ days, { $dayOfWeek: "$_id" } ] }
}
},
{
"$group": {
"_id": null,
"data": { $push: { k: "$day", v: "$count" } }
}
},
{
"$project": {
"data": { $arrayToObject: "$data" },
"_id": 0
}
}
])
我运行了这个,得到了想要的答案:
[
{
"data": {
"Sun": 30,
"Mon": 20
}
}
]
每当需要处理日期/时间值时,我建议使用库。这让你的生活轻松多了。看起来不错,只有一件事1->Mon和2->Tues。。。。7->使用$dayOfWeek时的星期日。这个数组应该是['',Mon','Tue','Wed','Thu','Fri','Sat','Sun']?