【问题标题】:how does Mongodb index works?Mongodb 索引是如何工作的?
【发布时间】:2012-11-03 09:28:12
【问题描述】:
I have a collection such as:
{u'_id': ObjectId('5094cc44e3f0f827b3618918'),
  u'xxx': 0},
 {u'_id': ObjectId('5094cc44e3f0f827b3618919'),
  u'xxx': 1},
 {u'_id': ObjectId('5094cc44e3f0f827b361891a'),
  u'xxx': 2},
 {u'_id': ObjectId('5094cc44e3f0f827b361891b'),
  u'xxx': 3},
 {u'_id': ObjectId('5094cc44e3f0f827b361891c'),
  u'xxx': 4}
...

当我创建索引时:

db.test.ensure_index([("_id",-1),("xxx",1)])
db.test.ensure_index([("xxx",1)])

然后,我使用如下解释:

db.test.find({"xxx":1}).sort("_id",-1).skip(5).limit(5).explain()

result is:
{u'allPlans': [{u'cursor': u'BtreeCursor _id_ reverse',
                u'indexBounds': {u'_id': [[{u'$maxElement': 1},
                                           {u'$minElement': 1}]]},
                u'n': 9,
                u'nscanned': 34,
               u'nscannedObjects': 34},
               {u'cursor': u'BtreeCursor xxx_1',
                u'indexBounds': {u'xxx': [[1, 1]]},
                u'n': 34,
                u'nscanned': 34,
                u'nscannedObjects': 34},
               {u'cursor': u'BtreeCursor _id_-1_xxx_1',
                u'indexBounds': {u'_id': [[{u'$maxElement': 1},
                                           {u'$minElement': 1}]],
                                 u'xxx': [[1, 1]]},
                u'n': 10,
                u'nscanned': 38,
                u'nscannedObjects': 10},
               {u'cursor': u'BasicCursor',
                u'indexBounds': {},
                u'n': 16,
                u'nscanned': 34,
                u'nscannedObjects': 34}],
 u'cursor': u'BtreeCursor xxx_1',
 u'indexBounds': {u'xxx': [[1, 1]]},
 u'indexOnly': False,
 u'isMultiKey': False,
 u'millis': 1,
 u'n': 5,
 u'nChunkSkips': 0,
 u'nYields': 0,
 u'nscanned': 34,
 u'nscannedAllPlans': 140,
 u'nscannedObjects': 34,
 u'nscannedObjectsAllPlans': 112,
 u'scanAndOrder': True,
 u'server': u'ubuntu:27017'}

从 n,nscanned 和 nscnnedObjects 的 num 中,我认为它应该使用 u'BtreeCursor id-1_xxx_1' 作为光标,但为什么它使用 u'cursor': u'BtreeCursor xxx_1', ? 谁能给我一些建议?我对索引优化有一点了解。

【问题讨论】:

  • 如果您在 javascript(官方 mongo shell 语言)中提供示例会有所帮助。
  • 那是一种python语言。我只想知道,当我使用find('xxx').sort('_id',-1)时,如何创建索引?
  • 在索引定义的末尾放一个你想要排序的字段:db.test.ensureIndex({xxx: 1, _id: -1})
  • 谢谢你,我试过了,解决方法没问题。但我有一些问题:在 中,有一个建议:使用 {'xxx':- 1,'_id':1},所以我们可以将最新的更新文档保存在内存中。但是这里似乎不太好。有什么我理解错了吗?
  • 排序顺序(1 或 -1)必须与索引顺序(1 或 -1)相同,以便排序可以从该索引中受益。如果您创建索引p:1 并使用p:-1 进行排序,它将不会使用该索引。

标签: mongodb indexing


【解决方案1】:

索引中字段的顺序很重要;查找和排序示例的最佳复合索引实际上是:

db.test.ensure_index([("xxx",1),("_id",-1)])

由于您的搜索条件在字段“xxx”上,因此将该字段放在索引中的第一个位置会比通过 _id 搜索然后过滤到与您的 xxx 条件匹配的文档找到更多的结果。

如果查看allPlans 中查询优化器考虑的每个计划的n 数字,BtreeCursor xxx_1 索引实际上返回的结果最多 (34)。其他索引返回 9、10 和 16 个结果......因此对于给定的搜索条件效率会降低。

有关索引优化的更多信息,这篇文章很有帮助:Optimizing MongoDB Compound Indexes

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2011-04-03
    • 2018-11-27
    • 1970-01-01
    相关资源
    最近更新 更多