Indexes
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.
Ascending
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")
Descending
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")
Compound Index
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"))
Text Index
To specify a text index key, use the text()
method.
The following example specifies a text index key for the description
field:
text("description")
Hashed Index
To specify a hashed index key, use the hashed()
method.
The following example specifies a hashed index key for the timestamp
field:
hashed("timestamp")
Geospatial Index
There are helpers for creating the index keys for the various geospatial indexes supported by MongoDB.
2dsphere
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")
2d
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")