Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB覆盖索引不工作_Mongodb_Covering Index - Fatal编程技术网

MongoDB覆盖索引不工作

MongoDB覆盖索引不工作,mongodb,covering-index,Mongodb,Covering Index,我有一份国家文件,看起来像: { "_id" : ObjectId("4e493af4140700590800154f"), "geoname_id" : "49518", "code" : "rw", "names" : { "en" : "Rwanda", "nl" : "Rwanda", "de" : "Ruanda" } } 为了仅在查询时触摸索引: db.countries.find({}, {"names.en":1, _id:0})

我有一份国家文件,看起来像:

{
  "_id" : ObjectId("4e493af4140700590800154f"),
  "geoname_id" : "49518",
  "code" : "rw",
  "names" : {
    "en" : "Rwanda",
    "nl" : "Rwanda",
    "de" : "Ruanda"
  }
}
为了仅在查询时触摸索引:

db.countries.find({}, {"names.en":1, _id:0})
我添加了以下索引:

db.countries.ensureIndex({"names.en":1})
据我所知,查询现在应该只涉及索引。 但是,.explain()告诉我查询根本没有使用任何索引:

{
  "cursor" : "BasicCursor",
  "nscanned" : 247,
  "nscannedObjects" : 247,
  "n" : 247,
  "millis" : 0,
  "nYields" : 0,
  "nChunkSkips" : 0,
  "isMultiKey" : false,
  "indexOnly" : false,
  "indexBounds" : {
  }
}
我认为原因可能是将输出完整的数据库(247个国家) 但这对我来说毫无意义。当国家/地区在索引中可用时 应该使用索引,对吗

有人有主意吗


干杯

它不使用索引的原因是因为您没有查询任何条件。如果没有查找条件,查询优化器将不会选择要使用的索引,因此无法作为覆盖索引

请尝试
db.countries.find({“names.en”:“luanda”},{“names.en”:1,{u id:0})。explain()
以验证使用索引条件时,它实际上会命中相应的索引


MongoDB需要足够聪明才能实现它可以使用索引来满足原始查询,但目前它没有。您可以使用.sort({“names.en”:1})让它也选择索引。

现在,您可以提示Mongo使用您想要的索引():


不过,我不确定这项功能是什么时候添加的。

使用排序将确保它只使用索引进行排序


将“查找”和“排序”视为两个独立的操作。

因此,要想完全清楚:只有在我能够以一种标准查询的方式重新构造文档时,才能从索引中获得完整的国家列表,比如说“语言:”en?不确定是否需要重新构造,因为{“names.en”:{$ne:“None”}as条件将与{}命中相同的列表。但是,是的,您需要条件才能命中当前的索引。感谢您的时间,Remon.hoi没有问题。请注意,使用.sort()时还可以使用索引。另外请注意,当输出字段之一是子文档中字段的虚线路径时,MongoDB当前不会使用覆盖索引。您可以观看并投票跟踪此问题。
db.countries.find({}, {"names.en":1, _id:0}).hint({"names.en":1})