MongoDB for Developers with Python Transcripts
Chapter: High-performance MongoDB
Lecture: Concept: Indexes via the shell
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
We've seen how powerful adding indexes to MongoDB is and I talked a little bit how the nested nature of these documents means
0:10
there's naturally fewer primary keys, so there's fewer on average actual indexes that get created just as part of working with the database;
0:19
so creating these indexes is even more important in document databases than it is in relational databases.
0:25
So here we are in the shell, this would be Robomongo or just the Mongo command line interface
0:31
and we can create an index on a collection by saying db.collection name so here we have cars.createIndex
0:36
and then we pass it two things, first one required, second one optional we pass it the actual fields we want to create the index on;
0:45
so here we have service_history.customer_rating so we could traverse this hierarchy if necessary
0:52
we just use that dot like we have been in the shell the whole time and then we say one or minus one, so do you want to sort ascending or descending.
1:00
And this mostly matters for either what you might consider the natural sort or if you're doing a composite key or a composite index
1:09
and that composite index is being used for sorting on both fields and all the orders have to line up exactly for the sort to use that index.
1:18
Then we can pass additional information, here we have background as true and the name, I like to name my indexes if I'm doing this shell
1:25
because then it's easier to see like okay why did I create this index here we want the customer ratings of service,
1:32
so that's pretty nice, background true, that's not the default but that means it will run basically in the background
1:39
without blocking the database operations, if you don't put that, when you hit go the database will stop doing any sort of database stuff
1:47
until this index is generated so be aware.