How to Perform Indexing in MongoDB using Java

Introduction

If you want MongoDB to process queries as efficiently as possible, it’s important to make good use of indexes. Indexes support the efficient execution of queries. They help MongoDB limit the number of documents it must inspect to complete a query. Without the help of indexes, MongoDB would have to scan each and every document in a collection in order to locate the documents that match the query criteria. In this article, we’ll learn the different types of indexes that are available in MongoDB such as single field index, hashed index and text index.

Prerequisites

We’ll be looking at many different types of indexes in this article, but before we begin, it’s important to review the prerequisites and make sure that all the system requirements are in place:

  • You’ll need to ensure that MongoDB and the MongoDB Java driver are both properly configured.

  • You’ll need to ensure that the latest version of the Java JDK is properly installed and configured.

  • You’ll also need to ensure that the MongoDB service is running.

NOTE: For the examples shown in this tutorial, we assume that the MongoDB version being used is 4.0 and the MongoDB Java Driver is 3.8.2.

What are Indexes in MongoDB?

An index is a special sort of data structure that can store a collection’s data in a format that’s fast and easy to traverse. Index entries are ordered in a way that makes it easy to support operations such as comparisons, equality matching and range queries. When you create an index on a field, the system will create an ordered list of the values for that field and store it separately. Every entry in this list will point to the corresponding entry in the original database table. When a user searches a table that has an index, what happens is that the system first searches the index table using a binary search algorithm, and then it returns the values from the original table. This is more efficient than the linear search that would be performed if there were no index in place.

Types of MongoDB Indexes

The following table lists the various types of MongoDB indexes:

Type of MongoDB IndexDescription
Default _idA MongoDB collection includes an index by default, the _id field. If no value given for _id, mongod creates an _id.
Single Field IndexThis is a simple index that indexes only one field within the MongoDB collection.
Compound IndexThe compound index requires more than one indexed field.
Geospatial IndexGeospatial indexes, which include 2d indexes and 2dsphere indexes, are used for coordinate data and GeoJSON objects.
Hashed IndexesHashed indexes use hashed-based sharding. They create a hash for the value of a field and spread the write among sharded instances.
Text IndexesText indexes in MongoDB look for a data string within a collection.

Instantiate a MongoDB object in Java that will be used to create indexes

Now that we’ve become familiar with the different types of MongoDB indexes, we can look at some code examples using Java. We’ll begin by using the MongoClient class from MongoDB to create a new instance of the client driver:

// connect to the MongoDB server
MongoClient mongoDbClient = MongoClient('mongodb://localhost:27017');

Next, we’ll use the MongoDB client instance to create a database and collection instance that can be used to make API calls:

// create a new database instance using `MongoDatabase`
// using `getDatabase()` method, MongoDB fetches
// the database name "SOME_DATABASE"
MongoDatabase dbMongo = mongo_client.getDatabase("SOME_DATABASE");

Create a new collection instance from dbMongo

// use MongoCollection<document> to access the `getCollection()` method
// so MongoDB can fetch the database's collection "SOME_COLLECTION"

MongoCollection<document> dbCollection = dbMongo.getCollection("SOME_COLLECTION");

NOTE : If the specified collection name doesn’t exist, MongoDB will create the collection automatically once an API call to create an index is made.

Create an Ascending Index in Java

Learn how to create a MongoDB index in an ascending order using Java

Create a Single Field index in Ascending Order

In our first example, we’ll create a single field index in ascending order. In the code shown below, we use the Indexes.ascending helper method to accomplish this:

dbCollection.create_index(Indexes.ascending("field1"));

This code will create a single field index in ascending order on the field1 field within the dbCollection collection.

Create a Compound Field Index in Ascending Order

In MongoDB, indexes on multiple fields, called compound indexes, are created by combining multiple index fields that are comma separated:

dbCollection.createIndex(Indexes.ascending("field1", "field2"));

In the code shown above, we create a compound index by passing multiple fields as a parameter in the Indexes.ascending() helper method. For this example, the fields being passed are “field1” and “field2”.

Create a Descending Index in Java

Next, we’ll see how to create a MongoDB index in descending order using Java. To accomplish this, we use the Indexes.descending() helper method:

dbCollection.create_index(Indexes.descending("some_field1"));

This code will create a single field index on the "some_field" field in descending order within the dbCollection collections.

Create a Compound Field Index in Descending Order

Compound indexes can also be created in descending order, as shown in the code below:

dbCollection.createIndex(Indexes.descending("some_field1", "some_field2"));

In this example, we created a compound index in descending order by passing multiple fields as a parameter to the Indexes.descending() helper method: “field1” and “field2”.

Create a Geospatial Index

In MongoDB, you can do queries on geospatial data, which refers to data stored either as a GeoJSON object or as coordinate pairs. There are two different index types that support geospatial queries: 2dsphere and 2d indexes.

Create a 2dsphere Index

A 2dsphere index is used to support queries where the data involves geometries on the Earth or an earth-like sphere. To create a 2dsphere index, we use the Indexes.geo2dsphere static helper method:

dbCollection.createIndex(Indexes.geo2dsphere("field.location"));

NOTE : A 2dsphere index must have a geometry value in a GeoJSON object or coordinate pair form.

Create a 2d Index

Another type of index used for geospatial queries is a 2d index. This index type is used for queries that support geometries on a two-dimensional plane– it’s generally used for legacy coordinate pairs in MongoDB 2.2. To create a 2d index, use the Indexes.geo2d static helper method:

collection.createIndex(Indexes.geo2d("field.location"));

Create MongoDB Hashed Indexes

In addition to the ascending and descending indexes we already discussed, you can also create hashed indexes. This is a type of index where the hash of a field’s value is indexed, used primarily in sharding scenarios. To create a hashed Index, use the Indexes.hashed() static helper method:

collection.createIndex(Indexes.hashed("field"));

Create MongoDB Text Indexes

In our final example, we’ll look at how to create a MongoDB text index. A text index provides a text search for a string within a MongoDB document. Text indexes can include a field whose value is either a string or a string of elements in an array.

To create a text index use the Indexes.text() helper method:

dbCollection.createIndex(Indexes.text("some_field3"));

Conclusion

If you feel like your queries aren’t being executed as quickly as you’d like, creating indexes can help. In this article, you were able to learn the different types of indexes that are available in MongoDB such as single field index, hashed index and text index. With this knowledge, you’ll be able to optimize the performance of your database and speed up your queries.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started

OR

Try CockroachDB
in Beta

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.