@@ -163,7 +163,7 @@ Compound Indexes
163
163
MongoDB supports "compound indexes," where a single index structure
164
164
holds references to multiple fields within a collection's
165
165
documents. Consider the collection ``products`` that holds documents
166
- that resemble the following example document:
166
+ that resemble the following example document:
167
167
168
168
.. code-block:: javascript
169
169
@@ -184,21 +184,24 @@ specify a single compound index to support both of these queries:
184
184
185
185
db.products.ensureIndex( { "item": 1, "stock": 1 } )
186
186
187
+ Note that that order of the fields in a compound index is very important.
188
+ Intuitively, the index above contains references to the documents sorted by
189
+ ``item``, and within each item, sorted by ``stock``.
187
190
MongoDB will be able to use this index to support queries that select
188
191
the ``item`` field as well as those queries that select the ``item``
189
- field **and** the ``stock`` field. However, these indexes will not
190
- support queries that select *only* the ``stock`` field.
192
+ field **and** the ``stock`` field. However, this index will not
193
+ be useful for queries that select *only* the ``stock`` field.
191
194
192
195
Ascending and Descending
193
196
````````````````````````
194
197
195
198
Indexes store references to fields in either ascending or descending
196
- order. The order of keys often doesn't matter because MongoDB can
197
- transverse the index in either direction. However, in compound
198
- indexes, for some kinds of sort operations, it's useful to have the
199
- fields running in opposite order .
199
+ order. For single-field indexes, the order of keys doesn't matter,
200
+ because MongoDB can traverse the index in either direction. However, for
201
+ compound indexes, it is occasionally useful to have the fields running in
202
+ opposite order relative to each other .
200
203
201
- To specify an index with an ascending order, use the following form:
204
+ To specify an index with a descending order, use the following form:
202
205
203
206
.. code-block:: javascript
204
207
@@ -213,6 +216,9 @@ following:
213
216
db.products.ensureIndex( { "field0": 1, "field1": -1 } )
214
217
215
218
.. TODO understand the sort operations better.
219
+ .. TODO Kevin's note: a good example here might be an index on
220
+ {"username" : 1, "timestamp" : -1} which would be helpful for listing
221
+ event history (most recent first) for all users (alphabetically).
216
222
217
223
.. _index-types-multikey:
218
224
0 commit comments