Databases Reference
In-Depth Information
Indexes on keys in embedded documents are identical to those on top-level keys, and
the two can be combined in compound indexes.
Indexing for Sorts
As your collection grows, you'll need to create indexes for any large sorts your queries
are doing. If you call sort on a key that is not indexed, MongoDB needs to pull all of
that data into memory to sort it. Thus, there's a limit on the amount you can sort
without an index: you can't sort a terabyte of data in memory. Once your collection is
too big to sort in memory, MongoDB will just return an error for queries that try.
Indexing the sort allows MongoDB to pull the sorted data in order, allowing you to
sort any amount of data without running out of memory.
Uniquely Identifying Indexes
Each index in a collection has a string name that uniquely identifies the index and is
used by the server to delete or manipulate it. Index names are, by default,
keyname1 _ dir1 _ keyname2 _ dir2 _..._ keynameN _ dirN , where keynameX is the index's key
and dirX is the index's direction (1 or -1). This can get unwieldy if indexes contain more
than a couple keys, so you can specify your own name as one of the options to
ensureIndex :
> db.foo.ensureIndex({"a" : 1, "b" : 1, "c" : 1, ..., "z" : 1}, {"name" : "alphabet"})
There is a limit to the number of characters in an index name, so complex indexes may
need custom names to be created. A call to getLastError will show whether the index
creation succeeded or why it didn't.
Unique Indexes
Unique indexes guarantee that, for a given key, every document in the collection will
have a unique value. For example, if you want to make sure no two documents can
have the same value in the "username" key, you can create a unique index:
> db.people.ensureIndex({"username" : 1}, {"unique" : true})
Keep in mind that insert , by default, does not check whether the document was ac-
tually inserted. Therefore, you may want to use safe inserts if you are inserting docu-
ments that might have a duplicate value for a unique key. This way, you will get a
duplicate key error when you attempt to insert such a document.
A unique index that you are probably already familiar with is the index on "_id" , which
is created whenever you create a normal collection. This is a normal unique index, aside
from the fact that it cannot be deleted.
 
Search WWH ::




Custom Search