微信小程序云开发-聚合函数连表查询
学习任何一门新的语言都很需要耐心的。
Collection.aggregate():发起聚合操作,定义完聚合流水线阶段之后需调用 end 方法标志结束定义并实际发起聚合操作
连表条件查询
exports.main = async (event, context) => {
.....省略了......
// 以下查询结果为: 满足match里面条件的accounts表数据和其有相对应user_id的users表数据的集合
return await db.collection(accounts)
.aggregate().match({
// 对主表accounts 添加筛选条件
group_id: event.groupId,
account_time: _.gte(lastTime),
utype: event.utype
})
.lookup({
// 左外连接副表users
from:users,
localField: user_id, // 指定主表的关联字段
foreignField: openid, // 指定副表的关联字段
as: userInfo // 把副表的查询结果放到userInfo对象里面
})
.end()
})
3个表也可以查询
exports.main = async (event, context) => {
try {
return await db.collection(settlement)
.aggregate().match({
settle_group_id: event.groupId
}).lookup({
from:users,
localField: settle_user_id,
foreignField: openid,
as: userInfo
})
.lookup({
from:groups,
localField: settle_group_id,
foreignField: group_id,
as: groupInfo
})
.end()
} catch (error) {
console.log(error)
}
}
清空表数据
db.collection(users).
where({
_id: _.all
})
.remove()
排序、限制查询条数
// 查找最近一次结算账单的时间
await db.collection(settlement)
.where({
settle_group_id: event.groupId
})
.field({
settle_date: true,
settle_user_id: true,
})
.orderBy(settle_date, desc) // 根据settle_date倒叙排
.limit(1) // 只查一条数据
.get()
.then(res => {
if(res.data.length > 0) {
const lastTime = res.data[0][settle_date]
}
})
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信小程序开发者工具详解
