mongodb - MongoDB:: MultiKey 字段的高效复合索引与排序
问题描述
我正在尝试使多键字段上的复合索引在排序时表现出色,但我似乎无法弄清楚。在这里使用带有wiredtiger的mongo 3.6。我的文档看起来像这样(删除了所有未被查询或不在索引中的内容):
{
_id: ObjectId(),
something: {
nested: [{_id: ObjectId()}, {_id: ObjectId()}, {_id: ObjectId()}]
},
another: {
thing: {
_id: ObjectId()
}
}
}
集合中有几百万个文档,我有以下索引:
{ "_id": 1 }
{ "something.nested._id": 1, "another.thing._id": 1, "_id": -1 }
{ "something.nested._id": 1, "_id": -1, "another.thing._id": 1 }
{ "_id": -1, "something.nested._id": 1, "another.thing._id": 1 } # this one only exists in a non-production system with far less documents
我正在尝试进行这样的查询(理想情况):
db.getCollection('whatever').find({"something.nested._id": ObjectId("5b88937a98162d5595b00000"), "another.thing._id": {"$ne": ObjectId("5b88937a98162d5595b00000")}} ).sort(_id: -1).limit(51)
explain 告诉我它正在IXSCAN
对_id
索引进行反向操作,然后在 aFETCH
上使用过滤器"something.nested._id"
and "another.thing._id"
。这会导致许多文档在找到足以满足限制之前被扫描。它没有使用任何包含"something.nested._id"
. 在暂存系统上,我尝试了一个带有_id
as 前缀的复合索引(我在某处读过),但这不是规划器的最佳选择,如果我强制它,我会得到类似的结果。
以任何方式改进此查询的唯一方法是摆脱.sort({_id: -1})
(它实际上是超快的),但自然排序可能是错误的,所以我不能真正使用它(即使在我所有的测试用例中它碰巧是正确的)。
那么是否有一个我只是缺少的有效索引,或者我们是否让我们的数据模型陷入困境?
解决方案
推荐阅读
- javascript - 替代复杂的 else if 梯子
- html - 在 CSS 中围绕中心旋转图像?
- google-chrome-headless - 在无头 chrome 中验证代理服务器 (ccproxy)
- c# - Microsoft graph 如何检测附件的内容类型(不是 .NET Core 3.1 中的内联附件)
- ios - RN从IOS中的URL获取blob下载docx或pdf
- python - 从媒体目录 Django 渲染图像
- sql - Oracle SQL - 带有迭代的案例语句
- python - 错误:列表索引应该是整数,但它是整数
- arrays - 将json数据更改为简单的php数组
- javascript - 从中介者模式javascript中的另一个类访问/调用类方法