mongodb - 使用 $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
出错。
我的问题是是否可以在不将变体数据移动到单独的集合中的情况下优化它以获得良好的性能(这是不可能的)。我考虑过使用“多键索引”,但我不知道如何在这里使用它们。
解决方案
推荐阅读
- python - 如果坐标可用,如何使用 python 访问数组中的“n”个段并对其进行算术运算?
- javascript - /subscriber/.gitkeep 目录或文件夹对 TypeORM 有什么作用?
- c# - 如何修复自 C# 以来的连接以远程连接到 dbf(共享文件)
- python - Pandas - 使用存储在变量中的列的索引值更改列序列
- javascript - 如何选择没有类组合的元素?
- r - 无法使用 RSelenium 打开 chrome 浏览器
- html - 如何在谷歌地图上浮动一个 div 并保持全屏显示?
- c++ - 如何动态分配我的数组,重新分配两次等?
- elasticsearch - 即使字段值不同,Elasticsearch function_score 查询 field_value_factor 也会分配相同的分数
- javascript - 回发链接按钮在最新版本的 chrome (73.0.3683.103) 中无法正常工作