Single Field Indexes
Overview
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 TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specific clock time.
When creating a single field index, you must specify the following:
The field on which to create the index
The sort order for the indexed values (ascending or descending)
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.
Sample Data
The examples in this guide use the movies
collection in the sample_mflix
database from the Atlas sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
Get Started with Atlas guide.
The following Kotlin data class models the documents in this collection:
data class Movie( val id: ObjectId, val title: String? = "", val type: String? = "", val genres: List<String>? = null, val cast: List<String>? = null, val plot: String? = "", )
Create Single Field Index
The following example creates an index in ascending order on the title
field:
collection.createIndex(Indexes.ascending(Movie::title.name))
The following is an example of a query that is covered by the index created in the preceding code example:
val filter = Filters.eq(Movie::title.name, "Batman") val sort = Sorts.ascending(Movie::title.name) val results = collection.find(filter).sort(sort) results.forEach { result -> println(result) }
Movie(id=573a1398f29313caabceb515, title=Batman, ...)
Additional Information
To learn more about single field indexes, see Single Field Indexes in the MongoDB Server manual.
API Documentation
To learn more about any of the methods discussed in this guide, see the following API documentation: