Mongodb扫描程序索引意外行为
我不了解mongodb的这种行为,我的收藏有以下索引(为了清晰起见,名称被简化),由~50k个文档组成Mongodb扫描程序索引意外行为,mongodb,Mongodb,我不了解mongodb的这种行为,我的收藏有以下索引(为了清晰起见,名称被简化),由~50k个文档组成 { "v" : 1, "key" : { "a" : 1, "b" : -1 }, "ns" : "db.articles", "name" : "a_1_b_-1", "background" : false, "dropDups" : false } 下面的查询 db.articles.find({
{
"v" : 1,
"key" : {
"a" : 1,
"b" : -1
},
"ns" : "db.articles",
"name" : "a_1_b_-1",
"background" : false,
"dropDups" : false
}
下面的查询
db.articles.find({ a: {"$in": ["foo", "bar"] } }).sort({b: -1}).limit(10).explain()
返回:
{
"cursor" : "BtreeCursor a_1_b_-1 multi",
"isMultiKey" : false,
"n" : 10,
"nscannedObjects" : 20,
"nscanned" : 21,
"nscannedObjectsAllPlans" : 68,
"nscannedAllPlans" : 105,
"scanAndOrder" : true,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"a" : [
[
"foo",
"foo"
],
[
"bar",
"bar"
]
],
"b" : [
[
{
"$maxElement" : 1
},
{
"$minElement" : 1
}
]
]
},
"server" : "localhost:27017"
}
“scanander”为true,这意味着索引中的顺序不能用于对返回集进行排序。这意味着当给定偏移量(即跳过10000)时,查询将阻塞,随后将返回“sort()的数据太多,没有索引。请添加索引或指定较小的限制”。
当查询更改为仅执行一次相等性检查时,将按预期使用索引:
db.articles.find({ a: "foo" }).sort({b: -1}).limit(10).explain()
结果集顺序现在是文档在索引中的顺序:
"scanAndOrder" : false
因此,这似乎与“$in”运算符在索引查找中的行为有关。MongoDB中的复合索引存储在树状数据结构中,例如,假设我们在
a
和b
字段上创建了索引,对于a
的每个值,都会有b
值的关联列表
BTree cursor的
$in
操作符返回a
值的引用列表,因此sort
操作符必须在排序之前合并多个b
值列表,之后不能使用索引。这篇博文将对此有所帮助:谢谢,这是一篇非常有用的文章