Databases Reference
In-Depth Information
can see that there are at least two documents for each collection: one for the collection
itself and one for each index it contains. For a collection with just the standard "_id"
index, its system.namespaces entries would look like this:
{ "name" : "test.foo" }
{ "name" : "test.foo.$_id_"}
If we add a compound index on the name and age keys, a new document is added to
system.namespaces with the following form:
{ "name" : "test.foo.$name_1_age_1" }
In Chapter 2 , we mentioned that collection names are limited to 121 bytes in length.
This somewhat strange limit is because the "_id" index's namespace needs 6 extra bytes
( ".$_id_" ), bringing the namespace length for that index up to a more sensical 127
bytes.
It is important to remember that the size of the collection name plus the index name
cannot exceed 127 bytes. If you approach the maximum namespace size or have large
index names, you may have to use custom index names to avoid creating namespaces
that are too long. It's generally easier just to keep database, collection, and key names
to reasonable lengths.
Changing Indexes
As you and your application grow old together, you may find that your data or queries
have changed and that the indexes that used to work well no longer do. You can add
new indexes to existing collections at any time with ensureIndex :
> db.people.ensureIndex({"username" : 1}, {"background" : true})
Building indexes is time-consuming and resource-intensive. Using the {"background" :
true} option builds the index in the background, while handling incoming requests. If
you do not include the background option, the database will block all other requests
while the index is being built.
Blocking lets index creation go faster but means your application will be unresponsive
during the build. Even building an index in the background can take a toll on normal
operations, so it is best to do it during an “off” time; building indexes in the background
will still add extra load to your database, but it will not bring it grinding to a halt.
Creating indexes on existing documents is slightly faster than creating the index first
and then inserting all of the documents. Of course, creating an index beforehand is an
option only if you're populating a new collection from scratch.
If an index is no longer necessary, you can remove it with the dropIndexes command
and the index name. Often, you may have to look at the system.indexes collection to
figure out what the index name is, because even the autogenerated names vary some-
what from driver to driver:
> db.runCommand({"dropIndexes" : "foo", "index" : "alphabet"})
 
Search WWH ::




Custom Search