1. 如何判断查询是否命中索引
游标调用explain函数会返回一个文档,用于描述当前查询的一些细节信息。
比如
01.
> db.blogs.find({
"comment.author"
:
"joe"
}).explain();
02.
{
03.
"cursor"
:
"BtreeCursor comment.author_1"
,
04.
"nscanned"
: 1,
05.
"nscannedObjects"
: 1,
06.
"n"
: 1,
07.
"millis"
: 70,
08.
"nYields"
: 0,
09.
"nChunkSkips"
: 0,
10.
"isMultiKey"
:
true
,
11.
"indexOnly"
:
false
,
12.
"indexBounds"
: {
13.
"comment.author"
: [
14.
[
15.
"joe"
,
16.
"joe"
17.
]
18.
]
19.
}
20.
}
1》 “cursor”:因为这个查询使用了索引,MongoDB中索引存储在B树结构中,所以这是也使用了BtreeCursor类型的游标。如果没有使用索引,游标的类型是BasicCursor。这个键还会给出你所使用的索引的名称,你通过这个名称可以查看当前数据库下的system.indexes集合(系统自动创建,由于存储索引信息,这个稍微会提到)来得到索引的详细信息。
2》 “nscanned”/“nscannedObjects”:表明当前这次查询一共扫描了集合中多少个文档,我们的目的是,让这个数值和返回文档的数量越接近越好。
3》 "n":当前查询返回的文档数量。
4》 “millis”:当前查询所需时间,毫秒数。
5》 “indexBounds”:当前查询具体使用的索引
01.
>
var
cursor = db.user.find({
"age"
:40,
"name"
:
"tim"
}).hint({
"age"
:1,
"name"
:1});
02.
> cursor.explain();
03.
{
04.
"cursor"
:
"BtreeCursor age_1_name_1"
,
05.
"nscanned"
: 1,
06.
"nscannedObjects"
: 1,
07.
"n"
: 1,
08.
"millis"
: 0,
09.
"nYields"
: 0,
10.
"nChunkSkips"
: 0,
11.
"isMultiKey"
:
false
,
12.
"indexOnly"
:
false
,
13.
"indexBounds"
: {
14.
"age"
: [
15.
[
16.
40,
17.
40
18.
]
19.
],
20.
"name"
: [
21.
[
22.
"tim"
,
23.
"tim"
24.
]
25.
]
26.
}
27.