索引
这Indexes类提供了静态工厂方法,用于创建MongoDB 索引键类型。每个方法都返回一个Bson
类型的实例,该实例可以用于createIndex()
方法。
您可以将Indexes
类的静态方法导入,如下所示
import org.mongodb.scala.model.Indexes._
本指南中的示例假设了这种静态导入。
升序
要指定升序索引键,请使用其中一个ascending()
方法。
以下示例指定了quantity
字段的升序索引键
ascending("quantity")
以下示例指定了一个由按升序排序的quantity
字段和按升序排序的totalAmount
字段组成的复合索引键
ascending("quantity", "totalAmount")
降序
要指定降序索引键,请使用以下任一descending()
方法。
以下示例在quantity
字段上指定了降序索引键
descending("quantity")
以下示例指定了一个复合索引键,由quantity
字段(降序排序)和totalAmount
字段(降序排序)组成
descending("quantity", "totalAmount")
复合索引
要指定复合索引,请使用compoundIndex()
方法。
以下示例指定了一个复合索引键,它由按升序排序的quantity
字段、按升序排序的totalAmount
字段以及按降序排序的orderDate
字段组成
compoundIndex(ascending("quantity", "totalAmount"), descending("orderDate"))
文本索引
要指定文本索引键,请使用text()
方法。
以下示例指定了description
字段的文本索引键
text("description")
哈希索引
要指定哈希索引键,请使用hashed()
方法。
以下示例为timestamp
字段指定了哈希索引键
hashed("timestamp")
地理空间索引
MongoDB支持的各种地理空间索引的索引键创建都有辅助方法。
2dsphere
要指定2dsphere索引键,请使用geo2dsphere()
方法之一。
以下示例在location
字段上指定了2dsphere
索引
geo2dsphere("location")
2d
要指定一个 2d
索引键,请使用 geo2d()
方法。
重要
二维索引用于存储在二维平面上作为点的数据,旨在用于MongoDB服务器2.2版及更早版本中使用的旧坐标对。
以下示例指定了在 points
字段上的 2d
索引
geo2d("points")