小程序雲開發 Aggregate 獲取時間範圍內出現的日期次數

Aggregate 技巧記錄

  const startDate = new Date('2020-03-01')
  const endDate = new Date('2020-04-01')
  const a = $.dateFromString({
    dateString: endDate.toJSON()
  }),
    b = $.dateFromString({
      dateString: startDate.toJSON()
    })
  console.log({ a, b });
  let x = await db.collection('xxx').aggregate()
    .addFields({
      matched: $.and([
        $.lte(['$createTime', a]),
        $.gte(['$createTime', b]),
        $.eq(['$key', 'xxxx'])
      ]),
    }).match({
      matched: !0,
    }).project({
      _id: 0,
      formatDate: $.dateToString({
        date: '$createTime',
        format: '%Y-%m-%d'
      }),
    }).group({
      _id: '$formatDate',
      count: $.sum(1),
    }).end()

輸出結果

{
	errMsg: "collection.aggregate:ok",
	list: [
		{_id: "2020-03-12", count: 12},
		{_id: "2020-03-11", count: 3},
 		{_id: "2020-03-10", count: 24},
 		{_id: "2020-03-07", count: 2}
 		]
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章