MongoTemplate提供了一些用于管理索引和集合的方法。这些方法被收集到一个名为IndexOperations的帮助接口中。您可以通过调用indexOps方法并传入集合名或实体的java.lang.Class来访问这些操作(集合名称来自 .class,或名称,或注释元数据)。
创建索引
您可以使用MongoTemplate类在集合上创建索引,以提高查询性能,还可以使用IndexDefinition、GeoSpatialIndex和TextIndexDefinition类创建标准、地理空间和文本索引。
mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));
mongoTemplate.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location"));
访问索引信息
IndexOperations接口具有getIndexInfo方法,该方法返回IndexInfo对象的列表。此列表包含在集合上定义的所有索引。下面的例子定义了Person类上具有age属性的索引:
template.indexOps(Person.class).ensureIndex(new Index().on("age", Order.DESCENDING).unique());
List indexInfoList = template.indexOps(Person.class).getIndexInfo();
// Contains
// [IndexInfo [fieldSpec={_id=ASCENDING}, name=_id_, unique=false, sparse=false],<