如何使用MongoDB聚合进行分页? [英] How to use MongoDB aggregation for pagination?

查看:226
本文介绍了如何使用MongoDB聚合进行分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个执行基本分页的聚合查询:

I want to perform an aggregation query that does basic pagination:

  1. 查找属于某个company_id
  2. 的所有订单
  3. order_number
  4. 排序
  5. 计算文档总数
  6. 跳至文档编号100,其余部分继续传递
  7. 将文件数限制为例如2并将其传递给
  8. 通过返回计数和从文档中选择的几个字段来完成
  1. Find all orders that belongs to a certain company_id
  2. Sort the orders by order_number
  3. Count the total number of documents
  4. Skips to e.g. document number 100 and passes on the rest
  5. Limits the number of documents to e.g. 2 and passes them on
  6. Finishes by returning the count and a selected few fields from the documents

这是查询的细分:

db.Order.collection.aggregate([

这会找到所有匹配的文档:

This finds all matching documents:

  { '$match'    : { "company_id" : ObjectId("54c0...") } },

这对文档进行排序:

  { '$sort'     : { 'order_number' : -1 } },

这将对文档进行计数并传递未修改的文档,但是我确定这样做是错误的,因为从这里开始,事情变得很奇怪:

This counts the documents and passes the unmodified documents, but I'm sure doing it wrong, because things turn weird from here:

  {
    '$group' : {
      '_id'     : null,
      'count'   : { '$sum' : 1 },
      'entries' : { '$push' : "$$ROOT" }
    }
  },

这似乎跳过了一些文档:

This seems to skip some documents:

  { "$skip"     : 100 },

这应该是用来限制文档的,但不是:

This is supposed to limit the documents, but it does not:

  { "$limit"    : 2 },

这确实会返回计数,但不会返回数组中的文档,而是返回包含每个字段的数组:

This does return the count, but it does not return the documents in an array, instead it returns arrays with each field:

  { '$project'  : {
      'count'     : 1,
      'entries'   : {'_id' : "$entries._id", 'order_number' : "$entries.order_number"}
    }
  }
])

这是结果:

[
  { "_id" : null,
    "count" : 300,
    "entries" : [
      {
        "_id" : [ObjectId('5a5c...'), ObjectId('5a5c...')],
        "order_number" : ["4346", "4345"]
      },
      {
        "_id" : [ObjectId('5a5c...'), ObjectId('5a5c...')],
        "order_number" : ["4346", "4345"]
      },
      ...
    ]
  }
]

我在哪里弄错了?

推荐答案

要计算总计返回一个子集,您需要对同一数据集应用分组和跳过/限制.为此,您可以使用构面

To calculate totals and return a subset, you need to apply grouping and skip/limit to the same dataset. For that you can utilise facets

例如显示第3页,每页显示10个文档:

For example to show 3rd page, 10 documents per page:

db.Order.aggregate([
    { '$match'    : { "company_id" : ObjectId("54c0...") } },
    { '$sort'     : { 'order_number' : -1 } },
    { '$facet'    : {
        metadata: [ { $count: "total" }, { $addFields: { page: NumberInt(3) } } ],
        data: [ { $skip: 20 }, { $limit: 10 } ] // add projection here wish you re-shape the docs
    } }
] )

它将返回包含2个字段的单个文档:

It will return a single document with 2 fields:

{
    "metadata" : [ 
        {
            "total" : 300,
            "page" : 3
        }
    ],
    "data" : [ 
        {
            ... original document ...
        }, 
        {
            ... another document ...
        }, 
        {
            ... etc up to 10 docs ...
        }
    ]
}

这篇关于如何使用MongoDB聚合进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆