首页 > 解决方案 > 使用 $unwind 和排序的 MongoDB 分页

问题描述

假设我有一个非常大的项目 MongoDB 数据库,其中每个项目都有一个嵌入式文档数组variants

{
  _id: 1,
  item: "item1",
  variants: [
    { type: "type1" },
    { type: "type2" }
  ]
}
{
  _id: 2,
  item: "item2",
  variants: [
    { type: "type1" },
    { type: "type3" }
  ]
}
...

我的目标是生成一个扁平的分页表并能够对每一列进行排序。

按变体类型排序的分页表:

 _id ↕ | item ↕ | type ↕  
-------+--------+--------
 1     | item1  | type1
 2     | item2  | type1   
 1     | item1  | type2
 2     | item2  | type3
...

< (1),2,3,4,5 ... 54323 >

我的方法是使用 MonogoDB 聚合管道为每个分页页面获取一个子集

db.items.aggregate([
  $unwind: {
    path: '$variants.type',
    includeArrayIndex: 'variant_index'
  },
  $sort: {
    'variants.type': 1
  }, {
    $skip: 0
  }, {
    $limit: 50
  }
])

不幸的是,对于大型数据集,这是一个非常昂贵的排序操作,甚至可能导致我的具体实现Sort exceeded memory limit of 104857600 bytes出错。

我的问题是是否可以在不将变体数据移动到单独的集合中的情况下优化它以获得良好的性能(这是不可能的)。我考虑过使用“多键索引”,但我不知道如何在这里使用它们。

标签: mongodbmongodb-query

解决方案


推荐阅读