By default, MongoDB scans every document in a collection to select those which match the query condition. If you have a query that uses a particular field and the query is used by the clients quite often, then we can create an index for the field so that the performance of the query can be increased. MongoDB offers different kinds of indexes, and the most common one is the single field index. Before we create this index, let's have a look at this command. We are searching a contact using a phone number, we can ask MongoDB as How did it arrive at this particular result by calling the explain function on the Find. The result shows which one is a winning plan and the winning plan says that it is called scan.
Basically it says the phone number was searched by matching this phone number for every document until it found or it is not found. This is quite inefficient if the query is repeatedly being used to avoid this We can now use a index. First, let's see what are the indexes that are currently available by giving DB dot contracts dot get indexes. And it says that there is only one single index on the field underscore ID underscore ID property is indexed by default for all collections. For example, db dot employees dot get indexes, also shows me that there is one index on the underscore ID. And we can go and check for all the collections and the story is saved.
Now let's create a new index for the phone property of contacts to do so DB dot contacts dot create index. And then we have to say phone to be indexed. Now it gives me a message saying that number of indexes before was one and number of indexes after is two. We can verify the same thing by issuing the command again, to get the indexes and do see that there are two of them. Now, we can also ask MongoDB to explain the query if we execute it now. And now you can see that out of many plans it came across with it now uses an eye x scan, which is nothing but index can if you want to drop the index DB dot context dot drop index, and then specify which is the property on which you want to drop the index.
So I have here phone as the property and then I can just say, drop indexes. Now it says number of indexes was two, which means now it should be only one we can also check it out by getting the indexes listed, which is that there is only one and also we can check the explained functions result which is now going back to the call scan.