Weekly, Monthly & Yearly Data Statistics using Aggregate in MongoDB

PHOTO EMBED

Sun Mar 20 2022 19:14:31 GMT+0000 (Coordinated Universal Time)

Saved by @youngDumb #mongo #nodejs

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  { timestamps: true }
);

module.exports = User = mongoose.model("User", userSchema);


// @routes  GET api/user/stats
// @desc    Get how many users are registered with in a year/month/week
// @access  Private - Admin
router.get("/stats", isAuthenticatedAndAdmin, async (req, res) => {
  User.aggregate([
    // { $match: { createdAt: { $gte: currentYear } } },
    {
      $project: {
        year: { $year: "$createdAt" },
        month: { $month: "$createdAt" },
        week: { $week: "$createdAt" },
      },
    },
    {
      $group: {
        _id: { year: "$year", month: "$month", week: "$week" },
        count: { $sum: 1 },
      },
    },
  ])
    .then((userStats) => res.status(200).json(userStats))
    .catch((err) => res.status(500).json(err));
});
content_copyCOPY