Docs Menu
Docs Home
/ / /
Scala
/

Multikey Indexes

On this page

  • Overview
  • Sample Data
  • Create a Multikey Index
  • Additional Information
  • API Documentation

Multikey indexes are indexes that improve the performance of queries on array-valued fields. You can create a multikey index on a collection by using the createIndex() method and the same syntax that you use to create a single field index.

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

  • The fields on which to create the index

  • The sort order for each field (ascending or descending)

The examples in this guide use the movies collection in the sample_mflix database from the Atlas sample datasets. To access this collection from your Scala application, create a MongoClient that connects to an Atlas cluster and assign the following values to your database and collection variables:

val database: MongoDatabase = mongoClient.getDatabase("sample_mflix")
val collection: MongoCollection[Document] = database.getCollection("movies")

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 multikey index. The following example creates an index in ascending order on the cast field:

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

You can verify that the index was created by calling the listIndexes() method. You should see an index for cast 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": {"cast": 1}, "name": "cast_1"}

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

val filter = and(equal("cast", "Aamir Khan"), equal("cast", "Kajol"))
collection.find(filter).first().subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_id":...,"title":"Fanaa",...,"cast": ["Aamir Khan", "Kajol", "Rishi Kapoor", "Tabu"],...}

To learn more about multikey indexes, see Multikey Indexes in the MongoDB Server manual.

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

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

Back

Compound