Node.js 猫鼬聚集群组按天、周、年
我正在使用nodejs和mongodb作为数据库 我的文件是:Node.js 猫鼬聚集群组按天、周、年,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我正在使用nodejs和mongodb作为数据库 我的文件是: { "_id": "58466d6a0b3f4d2e2fa22905", "updatedAt": "2016-12-06T07:48:58.435Z", "createdAt": "2017-12-06T07:48:58.435Z", "userId": "56d04e265a2100c72a311334", "__v": 0 } 用户将在客户端提供fromDate、toDate和fr
{
"_id": "58466d6a0b3f4d2e2fa22905",
"updatedAt": "2016-12-06T07:48:58.435Z",
"createdAt": "2017-12-06T07:48:58.435Z",
"userId": "56d04e265a2100c72a311334",
"__v": 0
}
用户将在客户端提供fromDate、toDate和frequency,其中频率值可以是0,1,2
其中0表示日,1表示周,2表示年
根据以上数据,我想生成报告
例如:如果用户给出fromDate=2016-12-1和toDate=2016-12-6
如果频率为0,则结果为
{
2016-12-01:{
count:1
}
2016-12-02:{
count:7
}
2016-12-06:{
count:8
}
}
{
2016-12-01 to 2016-12-06:{
count:16
}
}
{
2016:{
count:16
}
}
如果频率为1,则结果为
{
2016-12-01:{
count:1
}
2016-12-02:{
count:7
}
2016-12-06:{
count:8
}
}
{
2016-12-01 to 2016-12-06:{
count:16
}
}
{
2016:{
count:16
}
}
如果频率为2则结果为
{
2016-12-01:{
count:1
}
2016-12-02:{
count:7
}
2016-12-06:{
count:8
}
}
{
2016-12-01 to 2016-12-06:{
count:16
}
}
{
2016:{
count:16
}
}
其中count是文档数
我是这样做的:
var aggregate = [{
$match: {
createdAt: {
$gte: fromDate,
$lt: toDate
}
}
}, {
$group: {
// what should i will do here
},
count: {
$sum: 1
}
}
}]
return LoginReportModel.aggregate(aggregate).exec();
var frequency = 2
var frequencyDateFormatMap = {
0: '%Y-%m-%d',
1: '%U',
2: '%Y'
}
var frequencyDateFormat = frequencyDateFormatMap[frequency]
var aggregate = [
{$match: {
createdAt: {
$gte: fromDate,
$lt: toDate
}
}},
{$project: {
frequency: {
$dateToString: {
format: frequencyDateFormat,
date: '$createdAt'
}
}
}},
{$group: {
_id: '$frequency',
count: {
$sum: 1
}
}}
]
return LoginReportModel.aggregate(aggregate).exec()
或者任何一个知道其他更好的方法(如使用lodash)的人也欢迎使用
编辑:我还希望文档的计数在userId上是唯一的
查看有关的文档 你可以这样做:
var aggregate = [{
$match: {
createdAt: {
$gte: fromDate,
$lt: toDate
}
}
}, {
$group: {
// what should i will do here
},
count: {
$sum: 1
}
}
}]
return LoginReportModel.aggregate(aggregate).exec();
var frequency = 2
var frequencyDateFormatMap = {
0: '%Y-%m-%d',
1: '%U',
2: '%Y'
}
var frequencyDateFormat = frequencyDateFormatMap[frequency]
var aggregate = [
{$match: {
createdAt: {
$gte: fromDate,
$lt: toDate
}
}},
{$project: {
frequency: {
$dateToString: {
format: frequencyDateFormat,
date: '$createdAt'
}
}
}},
{$group: {
_id: '$frequency',
count: {
$sum: 1
}
}}
]
return LoginReportModel.aggregate(aggregate).exec()
你能帮我解决上述问题吗?我添加了一个示例,唯一的区别是对于频率1,它将周数作为组键输出,而不是像“2016-12-01到2016-12-06”这样的字符串。希望有帮助!谢谢你的帮助!这件事我也可以用$dayOfMonth和$year实现。。但主要问题是本周。。如何将本周编号转换为如上所述的日期,因为我需要在excel文件中写入上述数据以生成报告。此外,wnats的不同值计数取决于用户ID(已编辑)