1.从云数据库随机取出3条记录【这里使用了聚合操作aggregate】
let data = await db.collection('bookList').aggregate().sample({ size:3//随机取出3条记录 }).project({ chapter:false//当前字段不返回 }).end()
如何从随机中筛选出想要的数据?aggregate不能和where进行搭配,可使用match替代where
//随机取出三条记录 let data = await db.collection('bookList').aggregate().match({ bookType: event.params.bookType//查询的条件【玄幻,都市...】 }).sample({ size: 3 //随机取出3条记录 }).project({ chapter: false //当前字段不返回 }).end()
2.模糊查询并分页返回
result.data = await db.collection('bookList').where({ bookName: db.RegExp({ // 模糊查询 regexp: event.params.keyword, //从搜索栏中获取的value作为规则进行匹配。 options: 'i', //大小写不区分 }) }).field({ chapter: false //去除输出中的 chapter 字段 }).skip(event.params.pageSize * (event.params.pageNum - 1)).limit(event.params.pageSize).get()
3.查询分类
res = await db.collection('bookList').aggregate().sortByCount('$bookType').end()