数据格式模拟:
[{
_id:xxxxx,
name:xxx,
age:18,
health_records:[ky_start_at:开始时间,ky_end_at:'结束时间',....]
},
{
_id:xxxxx,
name:xxx,
age:20,
health_records:[ky_start_at:开始时间,ky_end_at:'结束时间',....]
}]
方法:
- 使用filter过滤符合范围的时间段
- 筛选:
$.and([$.gte(['$min', 30]), $.lte(['$max', 80])])
代码:
const db = cloud.database()
const _ = db.command
const $ = _.aggregate
let pageSize = 10
let stat_time = new Date('2021-12-1')
let end_time = new Date('2022-1-1')
let condition = _.or([{
phone: event.phone
},
{
name: event.phone
},
{
employee_id: event.phone
}
])
if (!event.phone) {
condition = {
_id: _.neq('')
}
}
// 默认时间是大于12月19日, 加以条件是大于选定的两个时间
return await cloud.database().collection('ky_records')
.aggregate() //可进行联表查询,返回联表查询对象
.project({
health_records: $.filter({
input: '$health_records',
as: 'item',
// cond: $.gte(['$$item.ky_start_at', stat_time])
cond: $.and([$.gte(['$$item.ky_start_at', stat_time]), $.lte(['$$item.ky_end_at', end_time])])
})
})
.match(condition)
.sort({
'create_at': -1
}) // 不排序没办法分页
.skip(event.page * pageSize)
.limit(pageSize)
.end()
结果: