利用java代码给mongo数据库加索引、删除索引等操作

网上搜了一下相关代码,不是互相抄瞎写就是答非所问,只好自己摸索着写一下,修改之后那这篇文章记录一下,免得以后遗忘。
我是在springboot项目中创建了一个类,需要创建索引的时候,在Test里写个函数跑一边就可以了。

package com.sohu.umab.usercenter.service.impl;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 给mongo数据库创建索引
 */
@Repository
public class CreateMongoIndex  {
    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 创建单个索引或者联合索引
     *
     * @param index_key 索引的名称,支持多个索引一起创建联合索引
     * @param collectionName 集合名称
     * @return
     */
    public boolean createInboxIndex(String collectionName, String... index_key) {
        boolean success = true;
        try {
            Index index = new Index();
            for (int i=0;i<index_key.length;i++){
                index.on(index_key[i],Sort.Direction.ASC);
            }
            mongoTemplate.indexOps(collectionName).ensureIndex(index);

        } catch (Exception ex) {
            success = false;
        }
        return success;
    }

    /**
     * 获取现有索引集合
     *
     * @return
     */
    public List<IndexInfo> getInboxIndex(String collectionName) {
        List<IndexInfo> indexInfoList = mongoTemplate.indexOps(collectionName).getIndexInfo();
        return indexInfoList;
    }

    /**
     * 删除索引
     *
     * @param indexName 索引的名称
     * @param collectionName 集合名称
     * @return
     */
    public boolean deleteInboxIndex(String indexName, String collectionName) {
        boolean success= true;
        try {
            mongoTemplate.indexOps(collectionName).dropIndex(indexName);
        } catch (Exception ex) {
            success= false;
        }
        return success;
    }

    /**
    * 获取mongo中数据集合的名称
    */
    public Set<String> getNames(){
        Set<String> res = mongoTemplate.getCollectionNames();
        return res;
    }
  
}
原文地址:https://www.cnblogs.com/47Gamer/p/14631261.html