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}
]
}