【微信小程序】【数据库】【聚合】能否先输出统计数值count,再输出聚合结果?
发布于 5 年前 作者 mbai 5788 次浏览 来自 官方Issues
const res = await db_contract.where({
    countrys:event.countrys
  }).count()//先获取符合结果的数量
  e.total = res.total
  if(e.total!=0){
  await db_contract.aggregate()
      .lookup({
        from:'MC_users',
        localField: 'no',
        foreignField: 'no',
        as'user',
      }).match({//匹配结果
        reach:false,
        countrys:event.countrys
      }).sort({
        _id:1
      }).//COUNT()这样不行
      .skip(event.start)
      .end()
      .then(r => {//返回匹配值,数据量大于20
        e.list = r.list
        console.log(r)
      })
      .catch(err =>{
        e.errCode = err.errCode
        console.error(err)
      })

这是我现在在用的代码,但是这样有点蠢,我只想要个计数和匹配数组,但是却做了两次查询,有没有什么办法能整合到一起吗?

3 回复

两次查询问题不大

const res = await db_contract.where({
    reach:false,
    countrys:event.countrys
  }).count()

若认为该回答有用,给回答者点个[ 有用 ],让答案帮助更多的人

const res = await db_contract.where({
    countrys:event.countrys
  }).count()//先获取符合结果的数量
  e.total = res.total

这部分可以不写,直接聚合,最后根据聚合结果判断

我也想知道,能不能count和get同时进行

回到顶部