A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and storage space to maintain the index data structure.
Let's connect to test collection and inspect how MongoDB processes a query
mongo testdb db.movies.find({title: new RegExp("godfather", "i")}).explain()
Create index
db.movies.ensureIndex({title: 1})
We only need to create an index once for a single collection. After initial creation, MongoDB automatically updates the index as data changes.
To list a collection’s indexes, use the db.collection.getIndexes()
.
To check the sizes of the indexes on a collection, use db.collection.stats()
.
In MeteorJS you can set indexing in SimpleSchema (package meteor-collection2). Simple snippet in CoffeeScript
MovieSchema = new SimpleSchema title: type: String label: "Title" max: 250 index: 1
Set to 1
or true
for an ascending index. Set to -1
for a descending index. Or you may set this to another type of specific MongoDB index, such as "2d"
. Indexes work on embedded sub-documents as well.
If you have created an index for a field by mistake and you want to remove or change it, set index
to false
.
Useful links