Database Reference
In-Depth Information
The next time you perform a search for any of the titles in the collection—assuming they are nested under
Tracklist —the titles will show up instantly. Next, you can take this concept one step further and use an entire (sub)
document as a key, as in this example:
> db.media.ensureIndex( { "Tracklist" : 1 } )
This statement indexes each element of the array, which means you can now search for any object in the array.
These types of keys are also known as multi keys . You can also create an index based on multiple keys in a set of
documents. This process is known as compound indexing . The method you use to create a compound index is mostly
the same; the difference is that you specify several keys instead of one, as in this example:
> db.media.ensureIndex({"Tracklist.Title": 1, "Tracklist.Length": -1})
The benefit of this approach is that you can make an index on multiple keys (as in the previous example, where
you indexed an entire subdocument). Unlike the subdocument method, however, compound indexing lets you
specify whether you want one of the two fields to be indexed in descending order. If you perform your index with the
subdocument method, you are limited to ascending or descending order only. There is more on compound indexes
in Chapter 10.
Surveying Index-Related Commands
So far you've taken a quick glance at one of the index-related commands, ensureIndex() . Without a doubt, this is the
command you will primarily use to create your indexes. However, you might also find a pair of additional functions
useful: hint() and min()/max() . You use these functions to query for data. We haven't covered them to this point
because they won't function without a custom index. But now let's take a look at what they can do for you.
Forcing a Specified Index to Query Data
You can use the hint() function to force the use of a specified index when querying for data. The intended benefit of
using this command is to improve the query performance. To see this principle in action, try performing a find with
the hint() function without defining an index:
> db.media.find( { ISBN: " 978-1-4302-5821-6"} ) . hint ( { ISBN: -1 } )
error: { "$err" : "bad hint", "code" : 10113 }
If you create an index on ISBN numbers, this technique will be more successful. Note that the first command's
background parameter ensures that the indexing is done on the background:
> db.media.ensureIndex({ISBN: 1}, {background: true});
> db.media.find( { ISBN: " 978-1-4302-5821-6"} ) . hint ( { ISBN: 1 } )
{ "_id" : ObjectId("4c45a5418e0f000000006291"), "Type" : "Book", "Title" : "Definitive Guide to
MongoDB, The", "ISBN" : " 978-1-4302-5821-6", "Author" : ["Hows, David","Membrey, Peter",
"Plugge, Eelco","Hawkins,Tim"], "Publisher" : [
{
"$ref" : "publisherscollection",
"$id" : ObjectId("4c4597e98e0f000000006290")
}
] }
 
Search WWH ::




Custom Search