获取每月创建的文档数(mongoose node js)

时间:2020-07-07 22:15:45

标签: node.js mongodb mongoose

我有以下模式

// User schema
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true,
    lowercase: true,
    validate(value) {
      if (!validator.isEmail(value)) {
        throw new Error('Email is Invalid")
      }
    }
  },
  password: {
    type: String,
    required: true,
    trim: true,
    minlength: 7,
    validate(value) {
      if (value.toLowerCase().includes('password')) {
        throw new Error('Password cannot contain "Password" !')
      }
    }
  },
  tokens: [{
    token: {
      type: String,
      required: true
    }
  }]
}, {
  timestamps: true
})

如何计算每个月创建的文档数?

示例输出:

[{
  "month":"june",
  "numberofdocuments":100
},{
  "month":"july",
  "numberofdocuments":50
}]

1 个答案:

答案 0 :(得分:0)

由于您拥有{ timestamps: true }作为选项,因此您将拥有猫鼬自动生成的字段createdAtupdateAt

我们可以使用MongoDB聚合根据createdAt的月份对文档进行分组

User.aggregate([ // User is the model of userSchema
  {
    $group: {
      _id: { $month: "$createdAt" }, // group by the month *number*, mongodb doesn't have a way to format date as month names
      numberofdocuments: { $sum: 1 }
    }
  },
  {
    $project: {
      _id: false, // remove _id
      month: { // set the field month as the month name representing the month number
        $arrayElemAt: [
          [
            "", // month number starts at 1, so the 0th element can be anything
            "january",
            "february",
            "march",
            "april",
            "may",
            "june",
            "july",
            "august",
            "september",
            "october",
            "november",
            "december"
          ],
          "$_id"
        ]
      },
      numberofdocuments: true // keep the count
    }
  }
])