Spring Boot集成mongodb数据库

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot集成mongodb数据库相关的知识,希望对你有一定的参考价值。

一.认识mongodb
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
二.Spring boot项目集成mongodb
1.添加mongodb依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2.配置mongodb的连接

spring:
    data:
            mongodb:
                #uri: mongodb://localhost:27017/data_exploration
                uri: mongodb://root:dhcc-mongodb@192.168.100.87:27017/data_exploration?authSource=admin&authMechanism=SCRAM-SHA-1

解析:以上uri分别代表本地配置和远程连接
3.操作数据库
(1)保存

@Repository
public class ExplorationJobDao {

    @Autowired
    MongoTemplate mongoTemplate;

    public void save(ExplorationJob explorationJob) {
        mongoTemplate.save(explorationJob);
    }
}

(2)根据ID修改一条数据(其原理先符合ID的数据,然后删除查询结果的第一条)

public void updateExecutionStatusById(int executionStatus, String jobId) {
            Query query = new Query(Criteria.where("jobId").is(jobId));
            Update update = new Update().set("executionStatus", executionStatus);
            mongoTemplate.updateFirst(query, update, ExplorationJob.class);
    }

(3)根据条修改多条数据(查询符合ID的所有数据,然后将所有数据修改)

public void update(BusinessExploration businessExploration) {
        Query query = new Query(Criteria.where("_id").is(businessExploration.getId()));
        Update update = new Update().set("sourceUnit", businessExploration.getSourceUnit())
                .set("appSystem", businessExploration.getAppSystem())
                .set("businessImplication", businessExploration.getBusinessImplication())
                .set("safetyRequire", businessExploration.getSafetyRequire());
        mongoTemplate.updateMulti(query, update, TableExploration.class);
    }

(4)删除(根据ID删除)

public void delExplorationJobById(String jobId) {
         Query query=new Query(Criteria.where("jobId").is(jobId));
         mongoTemplate.remove(query,ExplorationJob.class);
    }

(5)根据条件查询(根据ID查询)

public ExplorationJob getExplorationJobByJobId(String jobId) {
        Query query = new Query(Criteria.where("jobId").is(jobId));
        ExplorationJob explorationJob = mongoTemplate.findOne(query, ExplorationJob.class);
        return explorationJob;
    }

(6)查询所有


mongoTemplate.findAll(TableExploration.class);

(7)多条件动态查询

public List<ExplorationJob> getExplorationByCondition(ExplorationJob explorationJob) {
        Query query = new Query();
        if (explorationJob.getJobName() != null) {
             Pattern pattern = Pattern.compile("^.*" + explorationJob.getJobName() + ".*$", Pattern.CASE_INSENSITIVE);
             query.addCriteria(Criteria.where("jobName").regex(pattern));
        }
        if (explorationJob.getDsType() != null) {
            query.addCriteria(Criteria.where("dsType").is(explorationJob.getDsType()));
        }
        if (explorationJob.getExecutionStatus() != null) {
             query.addCriteria(Criteria.where("executionStatus").lte(explorationJob.getExecutionStatus()));
        }
        List<ExplorationJob> explorationJobs=mongoTemplate.find(query, ExplorationJob.class);
        return explorationJobs;
    }

(8)查询最大值

public Date getMaxExplorationDate(String tableName) {
        FindIterable<Document> iterable = mongoTemplate.getCollection("tableExploration")
                .find(new BasicDBObject("tableName", tableName)).sort(new BasicDBObject("explorationDate", -1)).skip(0)
                .limit(1);
        Document doc =null;
        if (getDocuments(iterable).size()>0) {
            doc=getDocuments(iterable).get(0);
            Date date = doc.getDate("explorationDate");
            return date;
        }else {
            return null;
        }
    }

    /**
     * 工具方法
     * 
     * @param iterable
     * @return
     */
    public static List<Document> getDocuments(FindIterable<Document> iterable) {
        List<Document> results = new ArrayList<Document>();
        if (null != iterable) {
            MongoCursor<Document> cursor = iterable.iterator();
            Document doc = null;
            while (cursor.hasNext()) {
                doc = cursor.next();
                results.add(doc);
            }
        }
        return results;
    }

(9)分组查询(这里还是用到了排序)

public List<TableExploration> getAllTableExplorationGroupByTableName(String jobId){
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("jobId").is(jobId)),
                Aggregation.sort(new Sort(Direction.DESC,"explorationDate")),
                Aggregation.group("tableName")
                .first("_id").as("tableName")
                .first("databaseType").as("databaseType")
                .first("databaseName").as("databaseName")
                .first("networkSituation").as("networkSituation")
                .first("userName").as("userName")
                .first("password").as("password")
                .first("url").as("url")
                .first("dataStorage").as("dataStorage")
                .first("dataIncrement").as("dataIncrement")
                .first("explorationDate").as("explorationDate")
                //.push("columnExplorations").as("columnExplorations")
                .first("jobId").as("jobId")
                );
        AggregationResults<TableExploration> aggregationResults= mongoTemplate.aggregate(aggregation, "tableExploration", TableExploration.class);
        List<TableExploration> tableExplorations=aggregationResults.getMappedResults();
        return tableExplorations;
                                                                                                                                                                                                【常用操作总结完毕】

以上是关于Spring Boot集成mongodb数据库的主要内容,如果未能解决你的问题,请参考以下文章

6.3 Spring Boot集成mongodb开发

spring boot + apache camel + mongodb 集成问题

如何在与MongoDB集成的Spring boot Elastic Search中实现对非结构化数据的搜索

在 Spring Boot Mongodb 中使用聚合框架按计数查找组

springboot 集成mongodb

Spring-boot集成pgmongo多数据源