In this recipe, we will look at querying data, analyzing its performance by explaining the query plan, and then optimizing it by creating indexes.
For the creation of indexes, we need to have a server up and running. A simple single node is what we will need. Refer to the Single node installation of MongoDB recipe in Chapter 1, Installing and Starting the MongoDB Server, to learn how to start the server. The data with which we will be operating needs to be imported into the database. The steps to import the data are given in the Creating test data recipe. Once we have this prerequisite, we are good to go.
We will trying to write a query that will find all the zip codes in a given state. To do this, perform the following steps:
Execute the following query to view the plan of a query:
> db.postalCodes.find({state:'Maharashtra'}).explain()
Take a note of the
cursor
,n
,nscannedObjects
, andmillis
fields in the result of...