We can force MongoDB to use an index by applying the hint() parameter:
> db.books.createIndex( { isbn: 1 }, { background: true } )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 8,
"numIndexesAfter" : 9,
"ok" : 1
}
The output from createIndex notifies us that the index was created ("ok" : 1), no collection was created automatically as part of index creation ("createdCollectionAutomatically" : false), the number of indexes before this index creation was 8, and now there are 9 indexes in total for this collection.
If we now try to search a book by isbn, we can use the explain() command to see the winningPlan subdocument where we can find which query plan was used:
> db.books.find({isbn: "1001"}).explain()
…
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"isbn" : 1,
"name" : 1
},
"indexName" : "isbn_1_name_1",
...
This means that an index with isbn:1 and name:1 was used instead of our newly-created index. We can also view our index in the rejectedPlans subdocument of the output:
…
"rejectedPlans" : [
{
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"isbn" : 1
},
"indexName" : "isbn_1",
...
This is in fact right as MongoDB is trying to reuse an index that is more specific than a more generic one.
We may have stumbled though in cases where our isbn_1 index is performing better than the isbn_1_name_1 one.
We can force MongoDB to use our newly created index as follows:
> db.books.find({isbn: "1001"}).hint("international_standard_book_number_index")
.explain()
{
...
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"isbn" : 1
},
...
Now the winningPlan subdocument contains our index, isbn_1, and there are no rejectedPlans elements: it's an empty array in the result set.
We cannot use hint() with the special type of text indexes.