Database Reference
In-Depth Information
7.2.1
Index types
All indexes in MongoDB use the same underlying data structure, but indexes with a
variety of properties are nevertheless permitted. In particular, unique, sparse, and
multikey indexes are frequently used, and here I describe them in some detail. 8
U NIQUE INDEXES
To c r e a t e a u n i q u e i n d e x , s p e c i f y t he unique option:
db.users.ensureIndex({username: 1}, {unique: true})
Unique indexes enforce uniqueness across all their entries. Thus if you try to insert a
document into this topic's sample application's users collection with an already-
indexed username value, then the insert will fail with the following exception:
E11000 duplicate key error index:
gardening.users.$username_1 dup key: { : "kbanker" }
If using a driver, this exception will be caught only if you perform the insert using
your driver's safe mode. See chapter 3 for a discussion of this.
If you need a unique index on a collection, it's usually best to create the index
before inserting any data. If you create the index in advance, you guarantee the unique-
ness constraint from the start. When creating a unique index on a collection that
already contains data, you run the risk of failure since it's possible that duplicate keys
may already exist in the collection. When duplicate keys exist, the index creation fails.
If you do find yourself needing to create a unique index on an established collec-
tion, you have a couple of options. The first is to repeatedly attempt to create the
unique index and use the failure messages to manually remove the documents with
duplicate keys. But if the data isn't so important, you can also instruct the database to
drop documents with duplicate keys automatically using the dropDups option. To take
an example, if your users collection already contains data, and if you don't care that
documents with duplicate keys are removed, then you can issue the index creation
command like this:
db.users.ensureIndex({username: 1}, {unique: true, dropDups: true})
Note that the choice of duplicate key documents to be preserved is arbitrary, so use
this feature with extreme care.
S PARSE INDEXES
Indexes are dense by default. This means that for every document in an indexed col-
lection, there will be a corresponding entry in the index even if the document lacks
the indexed key. For example, recall the products collection from your e-commerce
data model, and imagine that you've built an index on the product attribute
category_ids . Now suppose that a few products haven't been assigned to any
categories. For each of these categoryless products, there will still exist a null entry in
the category_ids index. You can query for those null values like so:
8
Note that MongoDB also supports spatial indexes, but because they're so specialized, I explain them sepa-
rately in appendix E.
Search WWH ::




Custom Search