Docs Menu
Docs Home
/ / /
Java Reactive Streams Driver

Optimize Queries by Using Indexes

On this page

  • Overview
  • Project Reactor Implementation
  • Sample Application
  • Single Field Index
  • Compound Index
  • Multikey Index
  • Geospatial Index
  • Unique Index
  • Wildcard Index
  • Clustered Index
  • Atlas Search Index Management
  • Create Search Index
  • List Search Indexes
  • Update Search Indexes
  • Delete Search Indexes
  • Text Index
  • Delete an Index

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.

1import com.mongodb.ConnectionString;
2import com.mongodb.MongoClientSettings;
3import com.mongodb.ServerApi;
4import com.mongodb.ServerApiVersion;
5
6import com.mongodb.client.model.ClusteredIndexOptions;
7import com.mongodb.client.model.CreateCollectionOptions;
8import com.mongodb.client.model.IndexOptions;
9import com.mongodb.client.model.Indexes;
10import com.mongodb.reactivestreams.client.*;
11import org.bson.Document;
12import org.reactivestreams.Publisher;
13import reactor.core.publisher.Flux;
14import reactor.core.publisher.Mono;
15
16public class IndexApp {
17 public static void main(String[] args) {
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connection string URI>";
20
21 // Construct a ServerApi instance using the ServerApi.builder() method
22 ServerApi serverApi = ServerApi.builder()
23 .version(ServerApiVersion.V1)
24 .build();
25
26 MongoClientSettings settings = MongoClientSettings.builder()
27 .applyConnectionString(new ConnectionString(uri))
28 .serverApi(serverApi)
29 .build();
30
31 // Create a new client and connect to the server
32 try (MongoClient mongoClient = MongoClients.create(settings)) {
33 MongoDatabase database = mongoClient.getDatabase("<database name>");
34 MongoCollection<Document> collection = database.getCollection("<collection name>");
35
36 // Start example code here
37
38 // End example code here
39 }
40 }
41}

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 Atlas Search indexes.

The following example creates an Atlas 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 Atlas 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 Atlas 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 an Atlas 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();

Back

Monitor Data Changes