我有一个关于如何正确编写索引以避免诉诸提示的问题。
示例“测试”集合架构
{
_id: ObjectId(<whatever>),
a: <whatever>,
b: <whatever>,
c: <whatever>,
d: <whatever>,
e: {
f: <whatever>,
g: <whatever>
}
}
“测试”指数
db.test.ensureIndex( { "a": NumberInt(1), "c": NumberInt(1), "_id": NumberInt(1), "d": NumberInt(1) },
{ name: "a_1_c_1__id_1_d_1", background: true } );
使用提示查询没有提示和查询...
> db.test.find({},{d:1}).explain();
{
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 752,
"nscannedObjects" : 752,
"nscanned" : 752,
"nscannedObjectsAllPlans" : 752,
"nscannedAllPlans" : 752,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 4,
"nChunkSkips" : 0,
"millis" : 5,
"indexBounds" : {
},
"server" : <whatever>
}
> db.test.find({},{d:1}).hint("a_1_c_1__id_1_d_1").explain();
{
"cursor" : "BtreeCursor a_1_c_1__id_1_d_1",
"isMultiKey" : false,
"n" : 752,
"nscannedObjects" : 752,
"nscanned" : 752,
"nscannedObjectsAllPlans" : 752,
"nscannedAllPlans" : 752,
"scanAndOrder" : false,
"indexOnly" : true,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"a" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
],
"c" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
],
"_id" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
],
"d" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
]
},
"server" : <whatever>
}
我(显然)喜欢使用覆盖索引的查询,但我不知道如何在不使用提示的情况下到达那里。可能吗?我更喜欢操纵索引而不是更改查询,但如果需要,可以选择更改查询。