Database Reference
In-Depth Information
Searching through indexed information is fast. Searching for non-indexed
information is slow, as each document needs to be checked to see if it's a match.
Tip
BSON allows you to store full arrays in a document; however, it would also be
beneficial to be able to create an index on an embedded key. Luckily, the developers of
MongoDB thought of this, too, and added support for this feature. Let's build on one of
the earlier examples in this chapter, adding another document into the database that has
embedded information:
> db.media.insert( { "Type" : "CD", "Artist" : "Nirvana","Title" :
"Nevermind", "Tracklist" : [ { "Track" : "1", "Title" : "Smells Like Teen
Spirit", "Length" : "5:02" }, {"Track" : "2","Title" : "In Bloom", "Length"
:
"4:15" } ] } )
{ "_id" : ObjectId("4c45aa2f8e0f000000006293"), "Type" : "CD", "Artist" :
"Nirvana", "Title" : "Nevermind", "Tracklist" : [
{
"Track" : "1",
"Title" : "Smells Like Teen Spirit",
"Length" : "5:02"
},
{
"Track" : "2",
"Title" : "In Bloom",
"Length" : "4:15"
}
] }
Next, you can create an index on the Title key for all entries in the track list:
> db.media.ensureIndex( { "Tracklist.Title" : 1 } )
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})
 
 
Search WWH ::




Custom Search