Optimize Queries by Using Indexes
On this page
Overview
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.
Project Reactor Implementation
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.
Sample Application
You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:
Create a new Java project in your IDE.
Install the Java Reactive Streams driver in your Java project.
Install the Project Reactor library in your Java project.
Copy the following code and paste it into a new Java file named
IndexApp.java
.Copy a code example from this page and paste it on the specified lines in the file.
1 import com.mongodb.ConnectionString; 2 import com.mongodb.MongoClientSettings; 3 import com.mongodb.ServerApi; 4 import com.mongodb.ServerApiVersion; 5 6 import com.mongodb.client.model.ClusteredIndexOptions; 7 import com.mongodb.client.model.CreateCollectionOptions; 8 import com.mongodb.client.model.IndexOptions; 9 import com.mongodb.client.model.Indexes; 10 import com.mongodb.reactivestreams.client.*; 11 import org.bson.Document; 12 import org.reactivestreams.Publisher; 13 import reactor.core.publisher.Flux; 14 import reactor.core.publisher.Mono; 15 16 public 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 }
Single Field Index
The following example creates an ascending index on the specified field:
Publisher<String> publisher = collection.createIndex(Indexes.ascending("<field name>")); Mono.from(publisher).block();
Compound Index
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();
Multikey Index
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();
Geospatial Index
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();
Unique Index
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();
Wildcard Index
The following example creates a wildcard index in the specified collection:
Publisher<String> publisher = collection.createIndex(Indexes.ascending("$**")); Mono.from(publisher).block();
Clustered Index
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();
Atlas Search Index Management
The following sections contain code examples that describe how to manage Atlas Search indexes.
Create Search Index
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();
List Search Indexes
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();
Update Search Indexes
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();
Delete Search Indexes
The following example deletes an Atlas Search index with the specified name:
Publisher<Void> publisher = collection.dropIndex("<index name>"); Mono.from(publisher).block();
Text Index
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();
Delete an Index
The following example deletes an index with the specified name:
Publisher<Void> publisher = collection.dropIndex("<index name>"); Mono.from(publisher).block();