在用户文档中,我已经注册了用户。我想通过API显示过去7天的统计数据。第一说-7用户,第二天-5用户,第三天-3用户.UserSchema包含-名称,电子邮件,createdAt等。我怎么能在Mongodb/猫鼬中做到这一点?
样本数据:
{
"_id": "612fa439ddb04331d6ea1e5d",
"name": "imran-1630512185253",
"createdAt": "2021-09-01T16:03:05.266Z",
},
{
"_id": "612fa439ddb04331d6ea1e5d",
"name": "imran-1630512185253",
"createdAt": "2021-08-31T16:03:05.266Z",
},
...........预期产出:
"filterData" : {
1st day: 3,
2nd day: 5,
3rd day: 3,
4th day: 8,
...
}使用这个API,我想要创建一个图表来显示统计数据。这个API应该提供哪一天,创建了多少用户。
发布于 2021-09-02 18:47:37
您所描述的查询是按日分组一系列文档,而这些文档包含UTC日期时间。
MongoDB内部将日期/时间存储为1970年1月1日以来的毫秒数,因此第一步需要计算每个文档的开始日期,然后根据该开始日期值进行分组。
如果使用的是MongoDB 5.0,则可以使用$dateTrunc操作符:
{$dateTrunc:{date:"$createdAt",unit:"day",timezone:"America/New_York"}}对于旧版本,可以计算表示一天开始的日期对象,也可以生成仅包含日期的字符串。
对于string选项:
{$concat: [
{$toString:{$year:{ date:"$createdAt", timezone:"America/New_York" }}},
"-",
{$toString:{$month:{ date:"$createdAt", timezone:"America/New_York" }}},
"-",
{$toString:{$dayOfMonth:{ date:"$createdAt", timezone:"America/New_York" }}},
]}因此,总的来说,聚合管道将是:
发布于 2021-09-02 17:50:44
你可以做这样的事
var d = new Date();
d.setDate(d.getDate()-7);然后
users.find({"createdAt": { $gt: d }})https://stackoverflow.com/questions/69034831
复制相似问题