ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2020-12-03 14:33:18  阅读:624  来源: 互联网

标签:index collectionName java mongo success return 索引 import


晚上搜了一下相关代码,不是互相抄瞎写就是答非所问,只好自己摸索着写一下,修改之后那这篇文章记录一下,免得以后遗忘。
我是在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;
    }
  
}

标签:index,collectionName,java,mongo,success,return,索引,import
来源: https://blog.csdn.net/weixin_45614626/article/details/110530108

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有