mongodbtamplate使用程序創建mongdb索引的解決方案

話不多說,直接上代碼:

 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類型的索引。

代碼實現截圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章