For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Optimize Queries by Using Indexes

On this page, you can see copyable code examples that show how to manage different types of indexes by using the Java Reactive Streams driver.

To use an example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <connection string URI>, with the relevant values for your MongoDB deployment.

This guide uses the Project Reactor library to consume Publisher instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation.

There are also other ways to consume Publisher instances. You can use one of many alternative libraries such as RxJava or call Publisher.subscribe() directly and pass your own implementation of a Subscriber.

This guide uses the Mono.block() method from Reactor to subscribe to a Publisher and block the current thread until the Publisher reaches its terminal state. To learn more about the Reactive Streams initiative, see Reactive Streams.

Important

Publishers Returned are Cold

All Publisher instances returned by the Java Reactive Streams driver methods are cold, which means that the corresponding operation does not happen unless you subscribe to the returned Publisher. We recommend only subscribing to the returned Publisher once, because subscribing more than once can lead to errors.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Create a new Java project in your IDE.

  2. Install the Java Reactive Streams driver in your Java project.

  3. Install the Project Reactor library in your Java project.

  4. Copy the following code and paste it into a new Java file named IndexApp.java.

  5. Copy a code example from this page and paste it on the specified lines in the file.

import com.mongodb.ConnectionString;import com.mongodb.MongoClientSettings;import com.mongodb.ServerApi;import com.mongodb.ServerApiVersion; import com.mongodb.client.model.ClusteredIndexOptions;import com.mongodb.client.model.CreateCollectionOptions;import com.mongodb.client.model.IndexOptions;import com.mongodb.client.model.Indexes;import com.mongodb.reactivestreams.client.*;import org.bson.Document;import org.reactivestreams.Publisher;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono; public class IndexApp { public static void main(String[] args) { // Replace the placeholder with your Atlas connection string String uri = "<connection string URI>"; // Construct a ServerApi instance using the ServerApi.builder() method ServerApi serverApi = ServerApi.builder() .version(ServerApiVersion.V1) .build(); MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)) .serverApi(serverApi) .build(); // Create a new client and connect to the server try (MongoClient mongoClient = MongoClients.create(settings)) { MongoDatabase database = mongoClient.getDatabase("<database name>"); MongoCollection<Document> collection = database.getCollection("<collection name>"); // Start example code here // End example code here } }}

The following example creates an ascending index on the specified field:

Publisher<String> publisher = collection.createIndex(Indexes.ascending("<field name>"));Mono.from(publisher).block();

The following example creates a compound index on the specified fields:

Publisher<String> publisher = collection.createIndex(Indexes.ascending("<field name 1>", "<field name 2>"));Mono.from(publisher).block();

The following example creates a multikey index on the specified array-valued field:

Publisher<String> publisher = collection.createIndex(Indexes.ascending("<array field name>"));Mono.from(publisher).block();

The following example creates a 2dsphere index on the specified field that contains GeoJSON objects:

Publisher<String> publisher = collection.createIndex(Indexes.geo2dsphere("<GeoJSON object field>"));Mono.from(publisher).block();

The following example creates a unique index on the specified field:

IndexOptions indexOptions = new IndexOptions().unique(true);Publisher<String> publisher = collection.createIndex(Indexes.ascending("<field name>"), indexOptions);Mono.from(publisher).block();

The following example creates a wildcard index in the specified collection:

Publisher<String> publisher = collection.createIndex(Indexes.ascending("$**"));Mono.from(publisher).block();

The following example creates a new collection with a clustered index on the _id field:

ClusteredIndexOptions clusteredIndexOptions = new ClusteredIndexOptions( Indexes.ascending("_id"), true); CreateCollectionOptions createCollectionOptions= new CreateCollectionOptions() .clusteredIndexOptions(clusteredIndexOptions); Publisher<Void> clusteredCollection = database.createCollection("<collection name>", createCollectionOptions);Mono.from(clusteredCollection).block();

The following sections contain code examples that describe how to manage MongoDB Search indexes.

The following example creates a MongoDB Search index on the specified field:

Document index = new Document("mappings", new Document("dynamic", true));Publisher<String> publisher = collection.createSearchIndex("<index name>", index);Mono.from(publisher).block();

The following example prints a list of MongoDB Search indexes in the specified collection:

ListSearchIndexesPublisher<Document> listIndexesPublisher = collection.listSearchIndexes(); Flux.from(listIndexesPublisher) .doOnNext(System.out::println) .blockLast();

The following example updates an existing MongoDB Search index with the specified new index definition:

Document newIndex = new Document("mappings", new Document("dynamic", true));Publisher<Void> publisher = collection.updateSearchIndex("<index name>", newIndex);Mono.from(publisher).block();

The following example deletes a MongoDB Search index with the specified name:

Publisher<Void> publisher = collection.dropIndex("<index name>");Mono.from(publisher).block();

The following example creates a text index on the specified string field:

Publisher<String> publisher = collection.createIndex(Indexes.text("<field name>"));Mono.from(publisher).block();

The following example deletes an index with the specified name:

Publisher<Void> publisher = collection.dropIndex("<index name>");Mono.from(publisher).block();