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
0:04 and I talked a little bit how the nested nature of these documents means
0:09 there's naturally fewer primary keys,
0:11 so there's fewer on average actual indexes
0:15 that get created just as part of working with the database;
0:18 so creating these indexes is even more important in document databases
0:22 than it is in relational databases.
0:24 So here we are in the shell, this would be Robomongo
0:27 or just the Mongo command line interface
0:30 and we can create an index on a collection by saying db.collection name
0:33 so here we have cars.createIndex
0:35 and then we pass it two things, first one required, second one optional
0:39 we pass it the actual fields we want to create the index on;
0:44 so here we have service_history.customer_rating
0:48 so we could traverse this hierarchy if necessary
0:51 we just use that dot like we have been in the shell the whole time
0:55 and then we say one or minus one,
0:57 so do you want to sort ascending or descending.
0:59 And this mostly matters for either what you might consider the natural sort
1:03 or if you're doing a composite key or a composite index
1:08 and that composite index is being used for sorting on both fields
1:12 and all the orders have to line up exactly for the sort to use that index.
1:17 Then we can pass additional information,
1:19 here we have background as true and the name,
1:21 I like to name my indexes if I'm doing this shell
1:24 because then it's easier to see like okay why did I create this index
1:28 here we want the customer ratings of service,
1:31 so that's pretty nice, background true, that's not the default
1:35 but that means it will run basically in the background
1:38 without blocking the database operations,
1:41 if you don't put that, when you hit go
1:43 the database will stop doing any sort of database stuff
1:46 until this index is generated so be aware.