如何使用Laravel查询MongoDB年度(创建)和Groupby年(创建)



我想使用laravel查询客户收集(mongodb(,它应该groupby('Year(create_at((和每年的记录编号

根据您的评论,还会在查询中添加日期范围。

db.customer.aggregate(
  [
    {
        $match: {
          '$and': [
            {
              'created_at': {
                $gte: new Date('2018-01-01')
              }, 
              'created_at': {
                $lte: new Date('2019-12-31')
              }
            }
          ]
        }
      }, {
        $group: {
          _id: {
            year: {
              $year: "$created_at"
            }
          }, 
          count: {
            $sum: 1
          }
        }
      }
    ]
  )

输出就像

[
  {
    "_id": {
      "year": "2018"
    },
    "count": 12
  },
  {
    "_id": {
      "year": "2019"
    },
    "count": 19
  }
]

最新更新