【问题标题】:MongoDB not using even the simplest indexMongoDB 甚至不使用最简单的索引
【发布时间】:2013-02-12 02:26:20
【问题描述】:

请看下面的例子。在我看来,查询应该被索引{a: 1} 覆盖,但是explain() 给了我一个indexOnly: false。我做错了什么?

> db.foo.save({a: 1, b: 2});
> db.foo.save({a: 2, b: 3});
> db.foo.ensureIndex({a: 1});
> db.foo.find({a: 1}).explain();
{
    "cursor" : "BtreeCursor a_1",
    "nscanned" : 6,
    "nscannedObjects" : 6,
    "n" : 6,
    "millis" : 0,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
        "a" : [
            [
                1,
                1
            ]
        ]
    }
}

【问题讨论】:

  • 它使用cursorBtreeCursor 所示的索引。显然有六个文档 - 是否有任何关于其他文档的东西导致了这种行为?
  • 我认为您对“indexOnly”的解释是错误的,请参阅docs.mongodb.org/manual/applications/indexes/…

标签: mongodb indexing mongodb-indexes


【解决方案1】:

索引仅表示覆盖查询 (http://docs.mongodb.org/manual/applications/indexes/#indexes-covered-queries),其中查询及其排序和数据都可以在单个索引中找到。

您的查询的问题:

db.foo.find({a: 1}).explain();

它必须检索完整的文档,这意味着它无法在索引中找到所有数据。相反,您可以使用:

db.foo.find({a: 1}, {_id:0,a:1}).explain();

这意味着您只投影a 字段,使整个查询适合索引,因此indexOnly 为真。

【讨论】:

    猜你喜欢
    • 2020-05-20
    • 2015-09-15
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    相关资源
    最近更新 更多