Docs Menu
Docs Home
/ / /
Scala
/

Indexes

On this page

  • Ascending
  • Descending
  • Compound Index
  • Text Index
  • Hashed Index
  • Geospatial Index
  • 2dsphere
  • 2d

The Indexes class provides static factory methods for the MongoDB index key types. Each method returns an instance of the Bson type, which can in turn be used with the createIndex() methods.

You can import the methods of the Indexes class statically, as shown in the following code:

import org.mongodb.scala.model.Indexes._

The examples in this guide assume this static import.

To specify an ascending index key, use one of the ascending() methods.

The following example specifies an ascending index key for the quantity field:

ascending("quantity")

The following example specifies a compound index key composed of the quantity field sorted in ascending order and the totalAmount field sorted in ascending order:

ascending("quantity", "totalAmount")

To specify a descending index key, use one of the descending() methods.

The following example specifies a descending index key on the quantity field:

descending("quantity")

The following example specifies a compound index key composed of the quantity field sorted in descending order and the totalAmount field sorted in descending order:

descending("quantity", "totalAmount")

To specify a compound index, use the compoundIndex() method.

The following example specifies a compound index key composed of the quantity field sorted in ascending order, followed by the totalAmount field sorted in ascending order, followed by the orderDate field sorted in descending order:

compoundIndex(ascending("quantity", "totalAmount"), descending("orderDate"))

To specify a text index key, use the text() method.

The following example specifies a text index key for the description field:

text("description")

To specify a hashed index key, use the hashed() method.

The following example specifies a hashed index key for the timestamp field:

hashed("timestamp")

There are helpers for creating the index keys for the various geospatial indexes supported by MongoDB.

To specify a 2dsphere index key, use one of the geo2dsphere() methods.

The following example specifies a 2dsphere index on the location field:

geo2dsphere("location")

To specify a 2d index key, use the geo2d() method.

Important

A 2d index is for data stored as points on a two-dimensional plane and is intended for legacy coordinate pairs used in MongoDB Server version 2.2 and earlier.

The following example specifies a 2d index on the points field:

geo2d("points")

Back

Updates