为了账号安全,请及时绑定邮箱和手机立即绑定

使用限制时,使用MongoDB获取文档总数

使用限制时,使用MongoDB获取文档总数

catspeake 2019-10-21 11:05:57
我对优化与MongoDB合作的“分页”解决方案感兴趣。我的问题很直接。我通常会限制使用该limit()功能返回的文档数。这迫使我发出一个没有该limit()功能的冗余查询,以便我也可以捕获查询中的文档总数,因此我可以将其传递给客户端,让他们知道他们将不得不发出额外的请求。检索其余文档。有没有一种方法可以将此压缩为1个查询?获取文档总数,但同时仅使用limit()?检索子集。与我正在解决的问题相比,有没有其他方法可以考虑这个问题?
查看完整描述

3 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

Mongodb 3.4引入了$facet聚合


它在同一组输入文档的单个阶段中处理多个聚合管道。


使用$facet和$group可以找到的文档,$limit并可以获得总数。


您可以在mongodb 3.4中使用以下聚合


db.collection.aggregate([

  { "$facet": {

    "totalData": [

      { "$match": { }},

      { "$skip": 10 },

      { "$limit": 10 }

    ],

    "totalCount": [

      { "$group": {

        "_id": null,

        "count": { "$sum": 1 }

      }}

    ]

  }}

])

即使您可以使用  $countmongodb 3.6中引入的聚合。


您可以在mongodb 3.6中使用以下聚合


db.collection.aggregate([

  { "$facet": {

    "totalData": [

      { "$match": { }},

      { "$skip": 10 },

      { "$limit": 10 }

    ],

    "totalCount": [

      { "$count": "count" }

    ]

  }}

])


查看完整回答
反对 回复 2019-10-21
?
当年话下

TA贡献1890条经验 获得超9个赞

时代变了,我相信你能达到什么OP是通过聚合与要求$sort,$group和$project。对于我的系统,我还需要从users集合中获取一些用户信息。希望这也可以回答有关此问题。下面是一个聚合管道。最后三个对象(排序,组和项目)是处理总计数,然后提供分页功能的对象。


db.posts.aggregate([

  { $match: { public: true },

  { $lookup: {

    from: 'users',

    localField: 'userId',

    foreignField: 'userId',

    as: 'userInfo'

  } },

  { $project: {

    postId: 1,

    title: 1,

    description: 1

    updated: 1,

    userInfo: {

      $let: {

        vars: {

          firstUser: {

            $arrayElemAt: ['$userInfo', 0]

          }

        },

        in: {

          username: '$$firstUser.username'

        }

      }

    }

  } },

  { $sort: { updated: -1 } },

  { $group: {

    _id: null,

    postCount: { $sum: 1 },

    posts: {

      $push: '$$ROOT'

    }

  } },

  { $project: {

    _id: 0,

    postCount: 1,

    posts: {

      $slice: [

        '$posts',

        currentPage ? (currentPage - 1) * RESULTS_PER_PAGE : 0,

        RESULTS_PER_PAGE

      ]

    }

  } }

])


查看完整回答
反对 回复 2019-10-21
  • 3 回答
  • 0 关注
  • 1494 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信