Docs Menu
Docs Home
/ / /
Scala
/

Single Field Indexes

On this page

  • Overview
  • Sample Data
  • Create Single Field Index
  • Additional Information
  • API Documentation

Single field indexes are indexes with a reference to a single field of a document in a collection. These indexes improve single field query and sort performance. They also support TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specified clock time.

When creating a single field index, you must specify the following details:

  • The field on which to create the index

  • The sort order for the indexed values as either ascending or descending

Note

The default _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 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.

To run the examples in this guide, you must include the following import statements in your file:

import org.mongodb.scala._
import org.mongodb.scala.model.Indexes
import org.mongodb.scala.model.IndexOptions._
import org.mongodb.scala.model.Filters._
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.{Failure, Success}
import java.util.concurrent.TimeUnit

Use the createIndex() method to create a single field index. The following example creates an index in ascending order on the title field:

val index = Indexes.ascending("title")
val observable = collection.createIndex(index)
Await.result(observable.toFuture(), Duration(10, TimeUnit.SECONDS))

You can verify that the index was created by using the listIndexes() method. You should see an index for title in the list, as shown in the following output:

collection.listIndexes().subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"v": 2, "key": {"title": 1}, "name": "title_1"}

The following is an example of a query that is covered by the index created on the title field:

val filter = equal("title", "Sweethearts")
collection.find(filter).first().subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_id":...,"plot":"A musical comedy duo...",
"genres":["Musical"],...,"title":"Sweethearts",...}

To view runnable examples that demonstrate how to manage indexes, see Optimize Queries by Using Indexes.

To learn more about single field indexes, see Single Field Indexes in the MongoDB Server manual.

To learn more about any of the methods discussed in this guide, see the following API documentation:

Back

Indexes