首页 > 解决方案 > 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". 在暂存系统上,我尝试了一个带有_idas 前缀的复合索引(我在某处读过),但这不是规划器的最佳选择,如果我强制它,我会得到类似的结果。

以任何方式改进此查询的唯一方法是摆脱.sort({_id: -1})(它实际上是超快的),但自然排序可能是错误的,所以我不能真正使用它(即使在我所有的测试用例中它碰巧是正确的)。

那么是否有一个我只是缺少的有效索引,或者我们是否让我们的数据模型陷入困境?

标签: mongodbmongodb-querywiredtiger

解决方案


推荐阅读