文档菜单
文档首页
/ / /
Scala
/

索引

本页内容

  • 升序
  • 降序
  • 复合索引
  • 文本索引
  • 哈希索引
  • 地理空间索引
  • 2dsphere
  • 2d

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索引键,请使用geo2dsphere()方法之一。

以下示例在location字段上指定了2dsphere索引

geo2dsphere("location")

要指定一个 2d 索引键,请使用 geo2d() 方法。

重要

二维索引用于存储在二维平面上作为点的数据,旨在用于MongoDB服务器2.2版及更早版本中使用的旧坐标对。

以下示例指定了在 points 字段上的 2d 索引

geo2d("points")

返回

更新