Escolar Documentos
Profissional Documentos
Cultura Documentos
∞,
5)
[-‐
[5,
10)
[10,
∞)
∞,
5)
buckets
[-‐
[5,
7) [7,
9) [9,
10)
[10,
∞)
buckets
{...}
{...}
{...}
{...}
{...}
{...}
{...}
{...}
{...}
{...}
{...}
Query for {a: 7}
With
Index
∞,
5)
buckets
[-‐
[5,
7) [7,
9) [9,
10)
[10,
∞)
buckets
{...} {...} {...} {...} {...} {...} {...} {...} {...} {...} {...}
db.posts.ensureIndex({“name”: 1})
1
=
ascending
-‐1
=
descending
Compound Indexes
db.posts.save({
title:
“My
First
blog”,
comments:
[
{author:
“James”,
ts
:
new
Date()}
]
});
db.posts.ensureIndex({“comments.author”:
1})
Multikeys
db.posts.ensureIndex({“tags”:
1})
Covered indexes
• New in 1.7.4
• Query can resolved in index only
• Need to exclude _id from items projected
db.posts.ensureIndex({“title”:
1})
db.posts.ensureIndex({“location”:
“2d”})
Listing Indexes
db.posts.getIndexes()
Dropping an Index
db.posts.dropIndex({“tags”:
1})
When is an Index Used?
Index
on
{a:
1}
db.coll.find({a:
0})
db.coll.find({a:
{$in:
[0,
2]}})
db.coll.find({a:
{$gt:
5}})
db.coll.count({a:
0})
db.coll.find().sort({a:
-‐1})
db.coll.find({a:
0},
{a:1,
_id:0})
Partially:
db.collection.find({b:
0})
Picking an a Index
find({x:
10,
y:
“foo”})
scan
terminate
index
on
x
db.collection.totalIndexSize()
Indexes Slow Down Writes
Does my query use an Index?
db.collection.find(query).explain();
Explain - Scan all documents
db.coll.find({title:”My
blog”}).explain();
{
"cursor"
:
"BasicCursor",
"indexBounds"
:
[
],
"nscanned"
:
57594,
"nscannedObjects"
:
57594,
"n"
:
3,
"millis"
:
108
}
Explain - Index used
db.coll.ensureIndex({title:1});
db.coll.find({title:”My
blog”}).explain();
{
"cursor"
:
"BtreeCursor
x_1",
"indexBounds"
:
[
],
"nscanned"
:
123,
"nscannedObjects"
:
123,
"n"
:
10,
"millis"
:
4
}
Explain - Covered Index used
db.coll.ensureIndex({title:1});
db.coll.find({title:”My
blog”},
{title:1,
_id:0}).explain();
{
"cursor"
:
"BtreeCursor
x_1",
"indexBounds"
:
[
],
"nscanned"
:
123,
"nscannedObjects"
:
123,
"n"
:
10,
"millis"
:
4,
"indexOnly"
:
true
}
download at mongodb.org
We’re Hiring !
alvin@10gen.com