node.js - Mongoose:每天创建多少用户

标签 node.js mongodb express mongoose

我需要计算上周每天创建的用户数量。我可以得到上周的总创建用户数

    var d = new Date();
    d.setDate(d.getDate() - 7);

    const data = await User.count({ "createdAt": { $gt: d } })
    return res.status(200).json({ error: false, data: data })

示例数据:

{
    "_id": "612fa439gdb04331d6ea1e5d",
    "name": "imran",
    "createdAt": "2021-09-01T16:03:05.266Z",
},
 {
    "_id": "612fa439ddb44331d6ea1e5d",
    "name": "Hossain",
    "createdAt": "2021-08-31T16:03:05.266Z",
},
...........

预期输出:

"user_count" : {
    02-09-2021: 3,
    01-09-2021: 5,
    31-08-2021: 3,
    30-08-2021: 5,
    ...
 }

使用这个API,我想创建一个图表来显示统计数据。该 API 应该提供哪一天创建了多少用户。我怎样才能做到这一点?

最佳答案

如果你想通过 mongodb 来做到这一点,你可以尝试转换你的 createdAt字段更改为实际日期,然后将其格式化为 yyyy-mm-dd 后按此日期进行分组。像这样的事情:

db.collection.aggregate([
  {
    $addFields: {
      createdAtDate: {
        $toDate: "$createdAt"
      },
      
    }
  },
  {
    $group: {
      _id: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$createdAtDate"
        }
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      count: 1,
      date: "$_id",
      _id: 0
    }
  }
])

这是 mongoplayground 上的一个示例:https://mongoplayground.net/p/8D9-kHZmPTo

关于node.js - Mongoose:每天创建多少用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69040640/

相关文章:

javascript - 将 http 请求中的数据保存到数组中,以 json 形式发送回客户端

javascript - 当 require() 处理文件时是否必须定义 module.exports ?

javascript - 查询 Mongodb 时混合字段和 js 函数

R : Updating an entry in mongodb using mongolite

javascript - 如何更新 Mongoose 嵌套数组文档

node.js - CORS 错误,但仅在 POST 请求时出现,尽管有 cors 配置(GET 没有问题)

node.js - Node JS 使用自定义 header 调用 GRPC 服务器

node.js - 如何在 node.js 中获取浏览器的大小?

mongodb组每2周

node.js - Nodemailer 的邮件在 Azure 服务器上无法工作