-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindexes.txt
387 lines (288 loc) · 13.5 KB
/
indexes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
.. _csharp-indexes:
=======
Indexes
=======
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: code example, Atlas search
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
.. toctree::
Atlas Search & Vector Search Indexes </fundamentals/indexes/search-indexes>
Overview
--------
In this guide, you can learn how to use indexes with the {+driver-long+}. Indexes can
improve the efficiency of queries and add functionality to querying and storing
documents.
Without indexes, MongoDB must scan *every* document in a collection to find the documents
that match each query. These collection scans are slow and can negatively affect the
performance of your application. However, if an appropriate index exists for a query,
MongoDB can use the index to limit the documents it must inspect.
Query Coverage and Performance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you execute a query against MongoDB, your query can include various
elements:
- Query criteria that specify fields and values that you are looking for
- Options that affect the query's execution, such as read concern
- Projection criteria to specify the fields you want MongoDB to return
- Sort criteria to specify the order of documents returned from MongoDB
When all the fields specified in the query, projection, and sort are in the same index,
MongoDB returns results directly from that index, also called a **covered query**.
For more information about how to ensure your index covers your query
criteria and projection, see the :manual:`Covered Query </core/query-optimization/#covered-query>`
section in the MongoDB server manual.
Operational Considerations
~~~~~~~~~~~~~~~~~~~~~~~~~~
To improve query performance, build indexes on fields that appear often in your
application's queries and operations that return sorted results. Each index that you add
consumes disk space and memory when active, so it might be necessary to track index memory
and disk usage for capacity planning. In addition, when a write operation updates an
indexed field, MongoDB also updates the related index.
Since MongoDB supports dynamic schemas, applications can query against fields whose names
cannot be known in advance or are arbitrary. MongoDB 4.2 introduced :manual:`wildcard indexes </core/index-wildcard/>`
to help support these queries. Wildcard indexes are not designed to replace workload-based
index planning.
For more information about designing your data model and choosing indexes
appropriate for your application, see the Server documentation on
:manual:`Indexing Strategies </applications/indexes>` and
:manual:`Data Modeling and Indexes </core/data-model-operations/#indexes>`.
Index Types
-----------
MongoDB provides several different index types to support querying
your data. The following sections describe the most common index types
and provide sample code for creating each index type.
.. note::
These example uses the ``sample_mflix.movies`` and ``sample_mflix.theaters`` collections
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see :ref:`csharp-quickstart`.
Single Field Indexes
~~~~~~~~~~~~~~~~~~~~
**Single-field indexes** are indexes with a reference to a single field within a
collection's documents. They improve single field query and sort performance, and support
:manual:`TTL Indexes </core/index-ttl>` that automatically remove documents from a
collection after a certain amount of time or at a specific clock time.
.. note::
The ``_id_`` index is an example of a single-field index. This index is automatically
created on the ``_id`` field when a new collection is created.
The following example creates an index in ascending order on the ``title`` field within
the ``sample_mflix.movies`` collection:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-single-index
:end-before: end-single-index
:dedent:
The following is an example of a query that is covered by the index
created in the preceding code snippet:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-single-index-query
:end-before: end-single-index-query
:dedent:
For more information, see :manual:`Single Field Indexes </core/index-single>` in the Server manual.
Compound Indexes
~~~~~~~~~~~~~~~~
**Compound indexes** hold references to multiple fields within a collection's documents,
improving query and sort performance.
The following example creates a compound index on the ``type`` and ``rated`` fields within
the ``sample_mflix.movies`` collection:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-compound-index
:end-before: end-compound-index
:dedent:
The following is an example of a query that is covered by the index
created in the preceding code snippet:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-compound-index-query
:end-before: end-compound-index-query
:dedent:
For more information, see :manual:`Compound Indexes </core/index-compound>` in the Server manual.
Multikey Indexes
~~~~~~~~~~~~~~~~
**Multikey indexes** collect and sort data from fields containing array values. You can
define a multikey index using the same syntax as a single field or compound index.
The following example creates a compound, multikey index on the ``rated``, ``genres``
(an array of Strings), and ``title`` fields within the ``sample_mflix.movies`` collection:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-multi-key-index
:end-before: end-multi-key-index
:dedent:
The following is an example of a query that is covered by the index created in the
preceding code snippet:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-multi-key-query
:end-before: end-multi-key-query
:dedent:
Multikey indexes behave differently from other indexes in terms of
query coverage, index bound computation, and sort behavior. To learn more about multikey
indexes, including a discussion of their behavior and limitations, see the
:manual:`Multikey Indexes page </core/index-multikey>` in the Server manual.
Clustered Indexes
~~~~~~~~~~~~~~~~~
**Clustered indexes** instruct a collection to store documents ordered by a key value.
To create a clustered index, specify the clustered index
option with the ``_id`` field as the key and the ``Unique`` property as
``true`` when you create your collection. A collection can only contain a single clustered
index. If you want to create a clustered index, then it must be specified when you create
a collection.
The following example creates a clustered index on the ``_id`` field while creating a new
``sample_mflix.reviews`` collection:
.. code-block:: csharp
var database = mongoClient.GetDatabase("sample_mflix");
var clusteredIndexOptions = new ClusteredIndexOptions<Review>
{
Key = Builders<Review>.IndexKeys.Ascending(r => r.Id),
Unique = true
};
database.CreateCollection("reviews", new CreateCollectionOptions<Review>
{
ClusteredIndex = clusteredIndexOptions
});
To learn more, see
:manual:`Clustered Indexes </reference/method/db.createCollection/#std-label-db.createCollection.clusteredIndex>` and
:manual:`Clustered Collections </core/clustered-collections>` in the Server manual.
Text Indexes
~~~~~~~~~~~~
**Text indexes** support text search queries on string content. These indexes can
include any field whose value is a string or an array of string elements. MongoDB supports
text search for various languages. You can specify the default language as an option when
creating the index.
.. tip::
MongoDB offers an improved full-text search solution,
:atlas:`Atlas Search </atlas-search/>`. To learn more about Atlas Search
indexes and how to use them, see the :ref:`search-indexes` section of this
guide.
Note that text indexes cannot support Atlas Search queries, and Atlas Search indexes
cannot support text queries.
Single Field
++++++++++++
The following example creates a text index on the ``plot`` field within the
``sample_mflix.movies`` collection:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-text-index
:end-before: end-text-index
:dedent:
The following query uses the text index created in the preceding code snippet:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: js
:start-after: begin-text-query
:end-before: end-text-query
:dedent:
Multiple Fields
+++++++++++++++
A collection can only contain one text index. If you want to create a
text index for multiple text fields, you must create a compound
index. A text search runs on all the text fields within the compound
index.
The following snippet creates a compound text index for the ``title`` and ``genre``
fields within the ``sample_mflix.movies`` collection:
.. code-block:: csharp
var indexModel = new CreateIndexModel<Movie>(Builders<Movie>.IndexKeys
.Text(m => m.Title)
.Text(m => m.Genre));
collection.Indexes.CreateOne(indexModel);
For more information, see :manual:`Compound Text Index Restrictions </core/indexes/index-types/index-text/text-index-restrictions/#compound-text-index>`
and :manual:`Text Indexes </core/index-text>` in the Server manual.
.. _geospatial-indexes:
Geospatial Indexes
~~~~~~~~~~~~~~~~~~
MongoDB supports queries of geospatial coordinate data using **2dsphere
indexes**. With a 2dsphere index, you can query the geospatial data for
inclusion, intersection, and proximity.
To create a 2dsphere index, you must specify a field that contains
only **GeoJSON objects**. For more details about this type, see :manual:`GeoJSON objects </reference/geojson>`
in the MongoDB Server manual.
The ``location.geo`` field in the following sample document from the
``sample_mflix.theaters`` collection is a GeoJSON Point object that describes the
coordinates of the theater:
.. code-block:: json
{
"_id" : ObjectId("59a47286cfa9a3a73e51e75c"),
"theaterId" : 104,
"location" : {
"address" : {
"street1" : "5000 W 147th St",
"city" : "Hawthorne",
"state" : "CA",
"zipcode" : "90250"
},
"geo" : {
"type" : "Point",
"coordinates" : [
-118.36559,
33.897167
]
}
}
}
The following example creates a ``2dsphere`` index on the ``location.geo`` field:
.. important::
Attempting to create a geospatial index on a field that is already covered by a geospatial index results in an error.
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-geospatial-index
:end-before: end-geospatial-index
:dedent:
The following is an example of a geospatial query using the "location.geo" index:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-geospatial-query
:end-before: end-geospatial-query
:dedent:
MongoDB also supports ``2d`` indexes for calculating distances on a Euclidean plane and
for working with the "legacy coordinate pairs" syntax used in MongoDB 2.2 and earlier.
To learn more, see :manual:`Geospatial Queries </geospatial-queries>` in the Server manual.
Unique Indexes
~~~~~~~~~~~~~~
**Unique indexes** ensure that the indexed fields do not store duplicate values. By
default, MongoDB creates a unique index on the ``_id`` field during the creation of a
collection. To create a unique index, specify the fields that you want to prevent
duplication on and set the ``Unique`` option to ``true``.
The following example creates a unique, descending index on the ``theaterId`` field within
the ``sample_mflix.theaters`` collection.
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-unique-index
:end-before: end-unique-index
:dedent:
If you attempt to perform a write operation that stores a duplicate value
that violates the unique index, MongoDB will throw an error that resembles
the following:
.. code-block:: none
:copyable: false
E11000 duplicate key error index
To learn more, see :manual:`Unique Indexes </core/index-unique>` in the Server manual.
Wildcard Indexes
~~~~~~~~~~~~~~~~
**Wildcard indexes** enable queries against unknown or arbitrary fields.
These indexes can be beneficial if you are using a dynamic schema.
The following example creates an ascending wildcard index on all
values of the ``location`` field within the ``sample_mflix.theaters`` collection,
including values nested in subdocuments and arrays:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-wildcard-index
:end-before: end-wildcard-index
:dedent:
For more information, see the :manual:`Wildcard Indexes</core/index-wildcard>` page in the
Server manual.
List Indexes
------------
You can use the `List() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoIndexManager-1.List.html>`__
method to retrieve a list of indexes in your collection.
The following example uses the ``List()`` method to list
all indexes in a collection:
.. literalinclude:: /includes/fundamentals/code-examples/Indexes.cs
:language: csharp
:start-after: begin-list-indexes
:end-before: end-list-indexes
:dedent: