也许问题是看起来像重复,但为它道歉。
我想汇总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和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 } }
];发布于 2020-12-14 08:47:15
你可以试试,
db.collection.aggregate([
{
$group: {
_id: {
year: { $year: "$createdAt" },
week: { $week: "$createdAt" }
},
createdAt: { $first: "$createdAt" },
count: { $sum: 1 }
}
}
])db.collection.aggregate([
{
$group: {
_id: {
year: { $year: "$createdAt" },
month: { $month: "$createdAt" }
},
createdAt: { $first: "$createdAt" },
count: { $sum: 1 }
}
}
])db.collection.aggregate([
{
$group: {
_id: { $year: "$createdAt" },
createdAt: { $first: "$createdAt" },
count: { $sum: 1 }
}
}
])您可以使用
createdAt字段从客户端语言更改日期格式!
https://stackoverflow.com/questions/65285364
复制相似问题