Compound Indexes
Overview
Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance.
When creating a compound index, you must specify the following:
The fields on which to create the index
The sort order for each field (ascending or descending)
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 a Compound Index
The following example creates a compound index on the type
and genre
fields, with
both fields indexed in ascending order:
collection.createIndex(Indexes.ascending(Movie::type.name, Movie::genres.name))
The following is an example of a query that uses the index created in the preceding code sample:
val filter = and( eq(Movie::type.name, "movie"), `in`(Movie::genres.name, "Drama") ) val sort = Sorts.ascending(Movie::type.name, Movie::genres.name) val results = collection.find(filter).sort(sort) results.forEach { result -> println(result) }
Movie(id=573a1392f29313caabcda755, title=China Seas, type=movie, genres=[Action, Drama, Adventure], ...) Movie(id=573a1392f29313caabcd9ca6, title=Scarface, type=movie, genres=[Action, Crime, Drama], ... ) Movie(id=573a1392f29313caabcdb258, title=The Hurricane, type=movie, genres=[Action, Drama, Romance], ...) Movie(id=573a1391f29313caabcd820b, title=Beau Geste, type=movie, genres=[Action, Adventure, Drama], ...) ...
Additional Information
To learn more about compound indexes, see Compound Indexes in the MongoDB Server manual.
To learn about effective indexing strategies using compound indexes, see The ESR Rule in the MongoDB Server manual.
API Documentation
To learn more about any of the methods discussed in this guide, see the following API documentation: