How to Create an Index using the MongoDB Shell
Introduction
Indexing data in a database makes querying for that information much more efficient. Without indexing MongoDB must scan every document individually while indexiing greatly reduces the number of documents MongoDB must scan.
How does an index work?
An index works by storing a specified field ordered by value so they’re efficiently searchable. The fields chosen for indexing are typically the fields that will be queried most often. If 99% of the time a collection is queried by the phone
field, then that’s a great field to index.
Prerequisites
- For this tutorial you should have MongoDB installed and running.
- You should also have a database and collection to experiment with indexing.
Goal
The goal of this tutorial is to create an index for our ‘Last Name’ field on our demoCollection
in our demoDatabase
.
STEP ONE
Select Database
First select the database you’ll be working with with the use <databaseName>
command.
1 | use demoDatabase |
STEP TWO
Pick an Index
Now we will print our collection using db.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | > db.demoCollection.find().pretty() { "_id" : ObjectId("5c786562ad685885625ab0b7"), "First Name" : "Donna", "Last Name" : "Dee", "Gender" : "Female", "Age" : 21 } { "_id" : ObjectId("5c786562ad685885625ab0b8"), "First Name" : "Alfred", "Last Name" : "Amus", "Gender" : "Male", "Age" : 39 } { "_id" : ObjectId("5c786562ad685885625ab0b9"), "First Name" : "Tessa", "Last Name" : "Sanders", "Gender" : "Female", "Age" : 39 } { "_id" : ObjectId("5c786562ad685885625ab0ba"), "First Name" : "Caitlyn", "Last Name" : "Anderson", "Gender" : "Female", "Age" : 21 } { "_id" : ObjectId("5c786562ad685885625ab0bb"), "First Name" : "Bob", "Last Name" : "Caster", "Gender" : "Male", "Age" : 65 } |
STEP THREE
Create Index with the createIndex() method.
Next, use the createIndex
method on the collection and pass in the field you want to index by with a value of 1.
1 2 3 4 5 6 7 | db.demoCollection.createIndex({"Last Name": 1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } |
You should see a "ok" : 1
, confirming success.
Conclusion
We have successfully indexed our collection on the Last Name
field which will make querying on the Last Name
field much more efficient. This is a simplistic example but there are tons of options with indexes including:
- Compound Index
- Multikey Index
- Geospatial Index
- Text Indexes
- Hashed Indexes
- Unique Indexes
- Partial indexes
- Sparse Indexes
- TTL Indexes
We hope you can use this basic example to move onto some of the more advanced concepts and to speed up your queries.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started