话不多说,直接上代码:
public boolean createMapNameIndex() {
IndexOptions indexOptions=new IndexOptions();
indexOptions.background(true);
//设置索引名
indexOptions.name("hanhan_index_mapname");
String resultStr=template.getCollection("maps")
.createIndex(new Document("mapname","hashed"),new IndexOptions().background(false).name("hanhan_index_mapname"));
System.out.println("index created");
return true;
}
对上面的参数略作解释:
indexOptions.name(“hanhan_index_mapname”);:这个里面设置的是你的索引名。
template.getCollection(“maps”):maps是你数据库的集合名字。
new Document(“mapname”,“hashed”):对名字为mapname这个字段创建hashed类型的索引。
代码实现截图: