Database Reference
In-Depth Information
the rule of thumb in MongoDB is to create an index for the same sort of scenarios where you'd want to create
one in MySQL.
Tip
You can create an index for this collection by invoking the following command:
> db.media.ensureIndex( { Title : 1 } )
This command ensures that an index will be created for all the Title values from all documents in the media
collection. The :1 at the end of the line specifies the direction of the index: 1 stores the items in ascending order,
whereas -1 stores them in descending order.
// Ensure ascending index
db.media.ensureIndex( { Title :1 } )
// Ensure descending index
db.media.ensureIndex( { Title :-1 } )
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 } )
 
Search WWH ::




Custom Search