微信小程序云开发-聚合函数连表查询

学习任何一门新的语言都很需要耐心的。

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']
      }
  })
  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值