Skip to content

Commit 305de8c

Browse files
committed
DOCSP-41142: Work with Indexes + Single Field Indexes
1 parent 8920746 commit 305de8c

File tree

5 files changed

+254
-6
lines changed

5 files changed

+254
-6
lines changed

source/includes/indexes/indexes.kt

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import com.mongodb.ConnectionString
2+
import com.mongodb.MongoClientSettings
3+
import com.mongodb.client.model.Indexes
4+
import com.mongodb.client.model.Filters
5+
import com.mongodb.client.model.Sorts
6+
import com.mongodb.kotlin.client.MongoClient
7+
import org.bson.codecs.pojo.annotations.BsonId
8+
import org.bson.types.ObjectId
9+
10+
// start-movie-class
11+
data class Movie(
12+
@BsonId
13+
val id: ObjectId,
14+
val title: String? = "",
15+
val genre: String? = "",
16+
val cast: List<String>? = null,
17+
val plot: String? = "",
18+
)
19+
// end-movie-class
20+
21+
fun main() {
22+
val uri = "<connection string URI>"
23+
24+
val settings = MongoClientSettings.builder()
25+
.applyConnectionString(ConnectionString(uri))
26+
.retryWrites(true)
27+
.build()
28+
29+
val mongoClient = MongoClient.create(settings)
30+
val database = mongoClient.getDatabase("sample_mflix")
31+
val collection = database.getCollection<Movie>("movies")
32+
33+
// start-remove-index
34+
collection.dropIndex("_title_")
35+
// end-remove-index
36+
37+
// start-index-single
38+
collection.createIndex(Indexes.ascending(Movie::title.name))
39+
// end-index-single
40+
41+
// start-index-single-query
42+
val filter = Filters.eq(Movie::title.name, "Batman")
43+
val sort = Sorts.ascending(Movie::title.name)
44+
val results = collection.find(filter).sort(sort)
45+
46+
results.forEach { result ->
47+
println(result)
48+
}
49+
// end-index-single-query
50+
}

source/includes/usage-examples/index-code-examples.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ fun main() {
2222
val collection = database.getCollection<Document>("<collection name>")
2323

2424
// start-single-field
25-
collection.createIndex(Indexes.ascending("<field name"))
25+
collection.createIndex(Indexes.ascending("<field name>"))
2626
// end-single-field
2727

2828
// start-compound

source/indexes.txt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,11 @@ Optimize Queries by Using Indexes
1818
:description: Learn how to use indexes by using the MongoDB Kotlin Sync driver.
1919
:keywords: query, optimization, efficiency, usage example, code example
2020

21-
.. TODO
22-
.. .. toctree::
23-
.. :titlesonly:
24-
.. :maxdepth: 1
21+
.. toctree::
22+
:titlesonly:
23+
:maxdepth: 1
2524

26-
.. /work-with-indexes
25+
/work-with-indexes
2726

2827
Overview
2928
--------

source/indexes/single-field-index.txt

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
.. _kotlin-sync-single-field-index:
2+
3+
====================
4+
Single-Field Indexes
5+
====================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: index, query, optimization, efficiency
19+
20+
Overview
21+
--------
22+
23+
:manual:`Single-field indexes </core/index-single/>` are indexes with a reference to a
24+
single field within a collection's documents. They improve single field query and sort
25+
performance, and support :manual:`TTL Indexes </core/index-ttl>` that automatically remove
26+
documents from a collection after a certain amount of time or at a specific clock time.
27+
28+
.. note::
29+
30+
The ``_id_`` index is an example of a single-field index. This index is automatically
31+
created on the ``_id`` field when a new collection is created.
32+
33+
Sample Data
34+
~~~~~~~~~~~
35+
36+
The examples in this guide use the ``movies`` collection in the ``sample_mflix``
37+
database from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
38+
free MongoDB Atlas cluster and load the sample datasets, see the
39+
:atlas:`Get Started with Atlas </getting-started>` guide.
40+
41+
The documents in this collection are modeled by the following {+language+} data class:
42+
43+
.. literalinclude:: /includes/indexes/indexes.kt
44+
:start-after: start-movie-class
45+
:end-before: end-movie-class
46+
:language: kotlin
47+
:copyable:
48+
49+
Create Single-Field Index
50+
-------------------------
51+
52+
The following example creates an index in ascending order on the ``title`` field:
53+
54+
.. literalinclude:: /includes/indexes/indexes.kt
55+
:start-after: start-index-single
56+
:end-before: end-index-single
57+
:language: kotlin
58+
:copyable:
59+
60+
The following is an example of a query that is covered by the index created in the preceding code example:
61+
62+
.. io-code-block::
63+
:copyable: true
64+
65+
.. input:: /includes/indexes/indexes.kt
66+
:start-after: start-index-single-query
67+
:end-before: end-index-single-query
68+
:language: kotlin
69+
:dedent:
70+
71+
.. output::
72+
:visible: false
73+
74+
Movie(id=573a1398f29313caabceb515, title=Batman, ...)
75+
76+
To learn more, see :manual:`Single Field Indexes </core/index-single>` in the {+mdb-server+} manual.

source/work-with-indexes.txt

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
.. _kotlin-sync-work-with-indexes:
2+
3+
=================
4+
Work with Indexes
5+
=================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: query, optimization, efficiency
19+
20+
.. toctree::
21+
22+
/indexes/single-field-index.txt
23+
24+
Overview
25+
--------
26+
27+
In this guide, you can learn how to use **indexes** with the {+driver-short+}.
28+
Indexes can improve the efficiency of queries and add additional functionality
29+
to querying and storing documents.
30+
31+
Without indexes, MongoDB must scan every document in a collection to find the
32+
documents that match each query. These collection scans are slow and can negatively affect
33+
the performance of your application. However, if an appropriate index exists for a query,
34+
MongoDB can use the index to limit the documents it must inspect.
35+
36+
Operational Considerations
37+
~~~~~~~~~~~~~~~~~~~~~~~~~~
38+
39+
To improve query performance, build indexes on fields that appear often in
40+
your application's queries and operations that return sorted results. Each
41+
index that you add consumes disk space and memory when active, so we recommend
42+
that you track index memory and disk usage for capacity planning. In addition,
43+
when a write operation updates an indexed field, MongoDB updates the related
44+
index.
45+
46+
Because MongoDB supports dynamic schemas, applications can query against fields
47+
whose names are not known in advance or are arbitrary. MongoDB 4.2 introduced
48+
:manual:`wildcard indexes </core/index-wildcard/>` to help support these
49+
queries. Wildcard indexes are not designed to replace workload-based index
50+
planning.
51+
52+
For more information about designing your data model and choosing indexes appropriate for your application, see the
53+
:manual:`Data Modeling and Indexes </core/data-model-operations/#indexes>` guide
54+
in the {+mdb-server+} manual.
55+
56+
Sample Data
57+
~~~~~~~~~~~
58+
59+
The examples in this guide use the ``movies`` collection in the ``sample_mflix``
60+
database from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
61+
free MongoDB Atlas cluster and load the sample datasets, see the
62+
:atlas:`Get Started with Atlas </getting-started>` guide.
63+
64+
Create an Index
65+
---------------
66+
67+
MongoDB supports several different index types to support querying your data.
68+
The following pages describe the most common index types and provide sample
69+
code for creating each index type.
70+
71+
- :ref:`kotlin-sync-single-field-index`
72+
73+
.. TODO: - :ref:`kotlin-sync-compound-index`
74+
.. TODO: - :ref:`kotlin-sync-atlas-search-index`
75+
76+
Remove an Index
77+
---------------
78+
79+
You can remove any unused index except the default unique index on the
80+
``_id`` field.
81+
82+
The following sections show how to remove a single index or to remove all
83+
indexes in a collection.
84+
85+
Delete a Single Index
86+
~~~~~~~~~~~~~~~~~~~~~
87+
88+
Pass an index name to the ``dropIndex()`` method to remove an index from a collection.
89+
90+
The following example removes an index with the name ``"_title_"`` from the ``movies``
91+
collection:
92+
93+
.. literalinclude:: /includes/indexes/indexes.kt
94+
:language: kotlin
95+
:start-after: start-remove-index
96+
:end-before: end-remove-index
97+
98+
.. note::
99+
100+
You cannot remove a single field from a compound text index. You must
101+
drop the entire index and create a new one to update the indexed
102+
fields.
103+
104+
Delete All Indexes
105+
~~~~~~~~~~~~~~~~~~
106+
107+
Starting with MongoDB 4.2, you can drop all indexes by calling the
108+
``dropIndexes()`` method on your collection:
109+
110+
.. code-block:: kotlin
111+
112+
collection.dropIndexes()
113+
114+
API Documentation
115+
~~~~~~~~~~~~~~~~~
116+
117+
To learn more about any of the methods or types discussed in this
118+
guide, see the following API documentation:
119+
120+
- `createIndex() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/create-index.html>`__
121+
- `createIndexes() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/create-indexes.html>`__
122+
- `dropIndex() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/drop-index.html>`__
123+
- `dropIndexes() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/drop-indexes.html>`__

0 commit comments

Comments
 (0)