gpt4 book ai didi

MongoDB 选择了错误的索引

转载 作者:行者123 更新时间:2023-12-02 04:11:57 25 4
gpt4 key购买 nike

我有一个名为 test 的 MongoDB 集合,其中包含以下两个简单文档:

    {
"first_name" : "John",
"last_name" : "Smith",
"age" : 25
}
{
"first_name" : "James",
"last_name" : "Bond",
"age" : 31
}

我还为此集合创建了以下索引:

    {
"first_name" : 1
}
{
"last_name" : 1
}
{
"age" : 1
}
{
"first_name" : 1,
"last_name" : 1,
"age" : 1
}

以下查询使用其对应的字段索引:

db.getCollection('test').find({first_name: 'John'});
db.getCollection('test').find({last_name: 'Smith'});
db.getCollection('test').find({age: 25});

但是当我执行以下查询时:

db.getCollection('test').find({first_name: 'John', last_name: 'Smith', age: 25});

它对字段 last_name 使用单个索引,而不是包含所有三个字段的复合索引。

Screenshot of explain

关于这个问题有什么想法/引用吗?
MongoDB版本:3.0.7

谢谢

最佳答案

MongoDB 查询规划器决定哪个索引对于给定查询最有效(此外,从 MongoDB 2.6 开始,它可以选择多个索引)。 Query planner documentation详细解释了它。

如果您希望它为最后一个查询选取 3 键复合索引,您有两个选择:

  1. 做出此决定会加快查询执行时间。基本上,您需要比 3 个文档大几个数量级的文档集大小。
  2. 使用hint()在你的光标上。您需要将索引名称作为 hint 方法的参数传递,您可以从 collection.getIndexes() 命令输出中找到该索引名称。

关于MongoDB 选择了错误的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36208347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com