猫鼬查询计数并返回一些结果列表

时间:2020-05-28 10:02:05

标签: mongodb mongoose

API看起来像:

{
  list: [], // length should lower than 20
  total: 160 // for frontend pagination
}

这是我的代码:

    const queryInstance = someModel.find(query)
    total = await queryInstance.countDocuments()
    list = await queryInstance.sort({ date: -1 }).skip(offset * pageSize).limit(pageSize * 1)
    return { total, list }

看起来像是第一次等待更改queryInstance,结果是list等于total

我的代码应该喜欢吗

   total = await someModel.find(query).countDocuments()
   list = await someModel.find(query).sort({ date: -1 }).skip(offset * pageSize).limit(pageSize * 1)

此查询两次数据库吗?我应该为此担心吗?

1 个答案:

答案 0 :(得分:0)

是的,您查询数据库两次。您可以做的是为您的(查询)和$ sortByCount(为您进行计数和排序)使用$ match的聚合,然后您可以执行以下操作:

db.collection_name.aggregate([match,sortByCount,skip,limit])

https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/ https://docs.mongodb.com/manual/reference/operator/aggregation/match/ https://docs.mongodb.com/manual/reference/operator/aggregation/skip/ https://docs.mongodb.com/manual/reference/operator/aggregation/limit/