可能问题看起来像是重复的,但对此表示歉意。
我想汇总每周、每月、每年的结果createdAt
没有时间和财产staffId
.
模型如下:
{
"_id" : ObjectId("5f351f3d9d90b1281c44c5dp"),
"staffId" : 12345,
"category" : "trend",
"page_route" : "http://example.com/rer",
"expireAt" : ISODate("2020-08-13T11:08:45.196Z"),
"createdAt" : ISODate("2020-08-13T11:08:45.199Z"),
"updatedAt" : ISODate("2020-08-13T11:08:45.199Z"),
"__v" : 0
}
{
"_id" : ObjectId("5f351f3d9d90b1281c44c5de"),
"staffId" : 12346,
"category" : "incident",
"page_route" : "http://example.com/rergfhfhf",
"expireAt" : ISODate("2020-08-14T11:08:45.196Z"),
"createdAt" : ISODate("2020-08-08T11:08:45.199Z"),
"updatedAt" : ISODate("2020-08-12T11:08:45.199Z"),
"__v" : 0
}
{
"_id" : ObjectId("5f351f3d9d90b1281c44c5dc"),
"staffId" : 12347,
"category" : "trend",
"page_route" : "http://example.com/rerrwe",
"expireAt" : ISODate("2020-08-13T11:08:45.196Z"),
"createdAt" : ISODate("2020-08-13T11:08:45.199Z"),
"updatedAt" : ISODate("2020-08-13T11:08:45.199Z"),
"__v" : 0
}
{
"_id" : ObjectId("5f351f3d9d90b1281c44c5dr"),
"staffId" : 12348,
"category" : "trend",
"page_route" : "http://example.com/rerrwe",
"expireAt" : ISODate("2020-08-12T11:08:45.196Z"),
"createdAt" : ISODate("2020-08-08T11:08:45.199Z"),
"updatedAt" : ISODate("2020-08-12T11:08:45.199Z"),
"__v" : 0
}
预期结果:示例 1) 每周
[
{_id: "2020-11-13", total: 2},
{_id: "2020-11-8", total: 2},
]
示例 2) 每月
[
{_id: "2020-11-8", total: 4},
]
同样对于每年...
我在用nodejs and mongoose实施API.
我很挣扎,但我无法达到预期的结果。
如果有人帮助我,那将是很大的帮助。
感谢各位专家。
我尝试过这样的事情:
[
{
$match: {
createdAt: { $gte: new Date(currentDate), $lt: new Date(nextDate) }
}
},
{
$project: {
_id: 1,
staffId: 1,
day: {
$dayOfMonth: "$createdAt"
},
month: {
$month: "$createdAt"
},
year: {
$year: "$createdAt"
}
}
},
{
$project: {
_id: 1,
staffId: 1,
datetime: {
$concat: [
{
$substr: ["$year", 0, 4]
},
"-",
{
$substr: ["$month", 0, 2]
},
"-",
{
$substr: ["$day", 0, 2]
}
]
}
}
},
{
$group: {
_id: {
createdAt: "$datetime",
staffId: "$staffId"
}
}
},
{
$group: {
_id: {$week:"$_id.createdAt"},
total: {
$sum: 1
}
}
},
{ $sort: { _id: 1 } }
];