【问题标题】:How to achieve pagination in mongoDB without using $facet as AZURE and AWS do not support it如何在不使用 $facet 的情况下在 mongoDB 中实现分页,因为 AZURE 和 AWS 不支持它
【发布时间】:2020-07-23 04:20:25
【问题描述】:

我收集了类似下面的东西

[
  {
    _id: id1,
    user: user1,
    city: "test1"
  },
  {
    _id: id2,
    user: user2,
    city: "test1"
  },
  {
    _id: id3,
    user: user3,
    city: "test2"
  },
.....
]

我想得到类似的东西,此外,我想根据 _id 等对结果进行排序。

[
  results: [
    {
      _id: id1,
      user: user1,
      city: "test1"
    },
    {
      _id: id1,
      user: user2,
      city: "test1"
    },
   ...
  ],
  totalResults: 220,
  pageNumber: 2
]

我的项目中也使用了moongoose

【问题讨论】:

  • 这能回答你的问题吗? Implementing pagination in mongodb
  • 不..这是关于光标的,我想发送其他详细信息,例如总结果数和当前页码。等以及结果
  • totalResults & pageNumber 是什么意思?对于代码分页,您可以将n num of results wantednth page 传递给DB(您可以返回n,但只是为了确保您何时请求20,但它只有10)..!!试试这个 :: (stackoverflow.com/questions/24160037/…)
  • 嗨@whoami,通过totalresults的意思是,我们有多少结果,我想从服务器发送这个信息,因为限制只会显示那个计数。例如,我有 72 个查询结果,我可以使用限制和跳过导航所有这些结果。但是我怎么知道我们有 72 个结果,因为 10 的限制将只发送 10 个查询结果
  • 好的,如果您需要 Coll & pagination 中的文档总数,$facet 将是最佳选择..

标签: mongodb mongoose azure-cosmosdb-mongoapi


【解决方案1】:
db.collection.aggregate([
  {
    "$match": {
      query
    }
  },
  {
    $project: {
      user: "$user"
    }
  },
  {
    "$sort": shortBy
  },
  {
    $group: {
      _id: null,
      postCount: {
        $sum: 1
      },
      results: {
        $push: '$$ROOT'
      }
    }
  },
  {
    $project: {
      total: '$postCount',
      results: {
        $slice: [
          '$results',
          skip,
          limit
        ]
      }
    }
  }
])

【讨论】:

    猜你喜欢
    • 2013-02-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2017-10-28
    • 2019-11-04
    • 2020-08-08
    • 2021-05-29
    相关资源
    最近更新 更多