Database Reference
In-Depth Information
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