Database Reference
In-Depth Information
Multikey indexes are always enabled in MongoDB. Anytime an indexed field con-
tains an array, each array value will be given its own entry in the index.
The intelligent use of multikey indexes is essential to proper MongoDB schema
design. This should be evident from the examples presented in chapters 4 through 6;
several more examples are provided in the design patterns section of appendix B.
7.2.2
Index administration
When it comes to administering indexes in MongoDB, there may be some gaps in
your operational knowledge. Here we'll see index creation and deletion in detail and
address questions surrounding compaction and backups.
C REATING AND DELETING INDEXES
By now you've created quite a few indexes, so there should be no mysteries surround-
ing the index creation syntax. Simply call one of the index creation helper methods,
either in the shell or with your language of choice, and a document defining the new
index will be placed into the special system.indexes collection.
Though it's usually easier to use a helper method to create an index, you can also
insert an index specification manually (this is what the helper methods do). You just
need to be sure you've specified the minimum set of keys: ns , key , and name . ns is the
namespace, key is the field or combination of fields to index, and name is a name used
to refer to the index. Any additional options, like sparse , can also be specified here.
So for example, let's create a sparse index on the users collection:
spec = {ns: "green.users", key: {'addresses.zip': 1}, name: 'zip'}
db.system.indexes.insert(spec, true)
If no errors are returned on insert, then the index now exists, and you can query the
system.indexes collection to prove it
db.system.indexes.find()
{ "_id" : ObjectId("4d2205c4051f853d46447e95"), "ns" : "green.users",
"key" : { "addresses.zip" : 1 }, "name" : "zip", "v" : 1 }
If you're running MongoDB v2.0 or later, you'll see that an extra key, v , has been
added. This version field allows for future changes in the internal index format but
should be of little concern to application developers.
To delete an index, you might think that all you need to do is remove the index
document from system.indexes , but this operation is prohibited. Instead, you must
delete indexes using the database command deleteIndexes . As with index creation,
there are helpers for deleting indexes, but if you want to run the command itself, you
can do that too. The command takes as its argument a document containing the col-
lection name and either the name of the index to drop or * to drop all indexes. To
manually drop the index you just created, issue the command like so:
use green
db.runCommand({deleteIndexes: "users", index: "zip"})
In most cases, you'll simply use the shell's helpers to create and drop indexes:
Search WWH ::




Custom Search