Mongodb - 没有使用索引

时间:2015-09-24 19:17:17

标签: mongodb indexing

我有一个包含大约42M文档的集合。我在这个集合上有2个索引,如下所示:

{
   "0" : {
      "v" : 1,
      "key" : {
         "_id" : 1
      },
      "name" : "_id_",
      "ns" : "ns.coll1"
   },
   "1" : {
     "v" : 1,
     "unique" : true,
     "key" : {
        "id" : 1
     },
     "name" : "id_1",
     "ns" : "ns.coll1"
   }
}

而且,这就是id字段的样子:

"_id" : ObjectId("55f9b6548aefbce6b2fa2fac"),
"id" : {
   "pid" : {
    "f1" : "val1",
    "f2" : "val2"
   }
},

使用索引字段对此集合进行非常简单的查询仍然不使用索引。

db.coll1.find({"id.pid.f1":"val1","id.pid.f2":"val2"}).explain();

{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 1,
    "nscannedObjects" : 42635482,
    "nscanned" : 42635482,
    "nscannedObjectsAllPlans" : 42635482,
    "nscannedAllPlans" : 42635482,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 333089,
    "nChunkSkips" : 0,
    "millis" : 51312,
    "filterSet" : false,
    "stats" : {
        "type" : "COLLSCAN",
        "works" : 42635484,
        "yields" : 333089,
        "unyields" : 333089,
        "invalidates" : 0,
        "advanced" : 1,
        "needTime" : 42635482,
        "needFetch" : 0,
        "isEOF" : 1,
        "docsTested" : 42635482,
        "children" : []
    }
}

我在这里缺少什么?在这里做一个全表扫描最好的方法,这就是为什么它没有使用索引? 感谢。

1 个答案:

答案 0 :(得分:0)

你必须在像这样的嵌套字段上创建索引

db.index.createIndex({" id.pid.f1":1," id.pid.f2":1})