Let's see how we can build an index on a field of a MongoDB collection using the mongo interactive shell.
1. Launch the mongo interactive shell and switch to a database named
testdb:
$ ./mongodb/bin/mongo MongoDB shell version: 1.8.1 connecting to: test > use testdb switched to db testdb >
2. Insert information about some of your favorite movies in a collection named
movies:
> db.movies.insert({name: "The Matrix", genre:"sci-fi", year: 1998}) > db.movies.insert({name: "Lord of the Rings", genre:"fantasy", year: 2002}) > db.movies.insert({name: "Saving Private Ryan", genre: "war", year: 1997}) > db.movies.insert({name: "Goodwill Hunting", genre: "drama", year: 1995}) > db.movies.insert({name: "The Dark Knight", genre: "action", year: 2008}) > db.movies.insert({name: "Inception", genre: "sci-fi", year: 2010})
3. Enter the following command to create an index on the
genre
field:> db.movies.ensureIndex({genre...