添加Maven依赖

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

配置Mongodb连接信息

spring:
data:
mongodb:
host: 10.30.29.246
port: 16030
authenticationDatabase: admin # 登录用户的认证库
database: nrdt
username: admin
password: QAZqaz@123321

通用服务(动态集合数据)

以下代码实现主要针对集合名称和字段都是未知的情况

@Slf4j
@Component
public class MongodbService { @Autowired
private MongoTemplate mongoTemplate; /**
* 新增集合(表)
*
* @param collName
*/
public void addCollection(String collName) {
Assert.notEmpty(collName, "collName");
boolean bol = mongoTemplate.collectionExists(collName);
if (!bol) {
mongoTemplate.createCollection(collName);
}
} /**
* 删除集合(表)
*
* @param collName
*/
public void dropCollection(String collName) {
Assert.notEmpty(collName, "collName");
boolean bol = mongoTemplate.collectionExists(collName);
if (bol) {
mongoTemplate.dropCollection(collName);
}
} /**
* 清空集合数据
*
* @param collName
*/
public void clearCollection(String collName) {
Assert.notEmpty(collName, "collName");
boolean bol = mongoTemplate.collectionExists(collName);
if (bol) {
mongoTemplate.remove(new Query(), collName);
}
} /**
* 修改字段名称
*
* @param collName
* @param oldName
* @param newName
* @return
*/
public boolean editField(String collName, String oldName, String newName) {
Assert.notEmpty(collName, "collName");
Assert.notEmpty(oldName, "oldName");
Assert.notEmpty(newName, "newName");
Query query = new Query();
Update update = new Update();
update.rename(oldName, newName);
UpdateResult result = mongoTemplate.updateMulti(query, update, collName);
return result.wasAcknowledged();
} /**
* 删除指定列
*
* @param collName
* @param field
*/
public boolean dropField(String collName, String field) {
Assert.notEmpty(collName, "collName");
Assert.notEmpty(field, "field");
Query query = new Query();
Update update = new Update();
update.unset(field);
UpdateResult result = mongoTemplate.updateMulti(query, update, collName);
return result.wasAcknowledged();
} /**
* 新增字段
*
* @param collName
* @param field
* @return
*/
public boolean addField(String collName, String field) {
Assert.notEmpty(collName, "collName");
Assert.notEmpty(field, "field");
Query query = new Query();
query.fields().include(field);
boolean bol = mongoTemplate.exists(query, collName);
if(!bol){
Update update = new Update();
update.set(field, 0.00d);
UpdateResult result = mongoTemplate.updateMulti(query, update, collName);
return result.wasAcknowledged();
}
return false;
} /**
* 新增多个字段
*
* @param collName
* @param fields
* @return
*/
public boolean addFields(String collName, List<String> fields) {
Assert.notEmpty(collName, "collName");
Assert.notNull(fields, "fields");
Update update = new Update();
boolean status = false;
for (String field : fields) {
Query query = new Query();
query.fields().include(field);
boolean bol = mongoTemplate.exists(query, collName);
if(!bol){
update.set(field, 0.00d);
status = true;
}
}
if(status){
UpdateResult result = mongoTemplate.updateMulti(new Query(), update, collName);
return result.wasAcknowledged();
} else {
return false;
}
} /**
* 批量新增行数据
*
* @param collName
* @param jsonArray
*/
public void insert(String collName, JSONArray jsonArray) {
Assert.notEmpty(collName, "collName");
Assert.notNull(jsonArray, "jsonArray");
mongoTemplate.insert(jsonArray, collName);
} /**
* 批量插入
* insert: 可以一次性插入一整个列表,不允许插入已存在的主键
* save: 需要遍历列表,进行一条一条的数据插入,主键存在则是修改
* @param collName
* @param list
*/
public void insert(String collName, List<Document> list) {
Assert.notEmpty(collName, "collName");
Assert.notNull(list, "list");
mongoTemplate.insert(list, collName);
} /**
* 修改行数据
*
* @param collName
*/
public void edit(String collName, JSONObject jsonObject) {
Assert.notEmpty(collName, "collName");
Assert.notNull(jsonObject, "jsonObject");
mongoTemplate.save(jsonObject, collName);
} /**
* 删除行数据
*
* @param collName
*/
public boolean remove(String collName, String[] ids) {
Assert.notEmpty(collName, "collName");
Assert.notNull(ids, "ids");
Query query = new Query(Criteria.where(MongoConstants.ID_COLUMN).in(ids));
DeleteResult result = mongoTemplate.remove(query, collName);
return result.wasAcknowledged();
} /**
* 抽样查询
* @param search
* @return
*/
public List<Document> getListSample(SearchVo search){
List<AggregationOperation> list = new ArrayList<>();
list.add(Aggregation.sample(search.getSampleSize()));
if(StrUtil.isNotEmpty(search.getColumns())){
list.add(Aggregation.project(search.getColumns().split(",")));
}
Aggregation aggregation = Aggregation.newAggregation(list);
return mongoTemplate.aggregate(aggregation, search.getCollName(), Document.class).getMappedResults();
} /**
* 查询样本时间的上下限
* @param collName
* @return
*/
public Map<String, Object> getTimes(String collName){
long startTime = System.currentTimeMillis();
Map<String, Object> map = new HashMap<>();
Assert.notEmpty(collName, "collName");
List<AggregationOperation> list = new ArrayList<>();
list.add(Aggregation.project(MongoConstants.TIME_COLUMN));
list.add(Aggregation.group().min(MongoConstants.TIME_COLUMN).as("minTime").max(MongoConstants.TIME_COLUMN).as("maxTime"));
Aggregation aggregation = Aggregation.newAggregation(list);
Document doc = mongoTemplate.aggregate(aggregation, collName, Document.class).getRawResults();
if(doc != null){
if(Convert.toInt(doc.get("ok")) == 1){
List<Document> results = doc.get("results", List.class);
if(results != null && results.size() > 0){
Document obj = results.get(0);
if(obj != null){
map.put("minTime", obj.getLong("minTime"));
map.put("maxTime", obj.getLong("maxTime"));
}
}
}
}
if(CollUtil.isEmpty(map)){
map.put("minTime", null);
map.put("maxTime", null);
}
log.info("查询样本上下限时间,耗时:{}秒", (System.currentTimeMillis() - startTime)/1000);
return map;
}
/**
* 分页查询表数据
*
* @param search
* @return
*/
public TableDataInfo getPage(SearchInput search) {
List<JSONObject> list = new ArrayList<>();
Query query = getQuery(search);
long count = mongoTemplate.count(query, search.getCollName());
if (count > 0L) {
if (StrUtil.isEmpty(search.getSort())) {
// 默认根据时间排序
search.setSort(MongoConstants.TIME_COLUMN);
}
// 分页:跳过前skip个文档,返回接下来的pageSize个文档
int skip = (search.getPageNum() - 1) * search.getPageSize();
query = query.with(Sort.by(search.getSort()).ascending()).skip(skip).limit(search.getPageSize());
list = mongoTemplate.find(query, JSONObject.class, search.getCollName());
}
TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS);
rspData.setRows(list);
rspData.setMsg("查询成功");
rspData.setTotal(count);
return rspData;
} /**
* 根据条件查询数据量
*
* @param search
* @return
*/
public long getCount(SearchInput search) {
Query query = getQuery(search);
return mongoTemplate.count(query, search.getCollName());
} /**
* 分页查询集合的数据
*
* @param search
* @return
*/
public List<Document> getListDoc(SearchInput search) {
Query query = getQuery(search);
if (StrUtil.isNotEmpty(search.getSort())) {
query = query.with(Sort.by(search.getSort()).ascending());
}
int skip = (search.getPageNum() - 1) * search.getPageSize();
query = query.skip(skip).limit(search.getPageSize());
return mongoTemplate.find(query, Document.class , search.getCollName());
} /**
* 随机查询一条数据
* @param collName
* @return
*/
public JSONObject getOne(String collName){
Query query = new Query();
query = query.limit(1);
return mongoTemplate.findOne(query, JSONObject.class, collName);
} public Query getQuery(SearchInput search) {
Criteria criteria = new Criteria();
List<Criteria> criteriaList = new ArrayList<>();
if (StrUtil.isNotEmpty(search.getBeginTime())) {
criteriaList.add(Criteria.where(MongoConstants.TIME_COLUMN).gte(Convert.toLong(search.getBeginTime())));
}
if (StrUtil.isNotEmpty(search.getEndTime())) {
criteriaList.add(Criteria.where(MongoConstants.TIME_COLUMN).lte(Convert.toLong(search.getEndTime())));
}
if (criteriaList.size() > 0) {
criteria.andOperator(criteriaList);
}
Query query = new Query(criteria);
if (StrUtil.isNotEmpty(search.getColumns())) {
query.fields().include(search.getColumns().split(","));
}
if(StrUtil.isNotEmpty(search.getExclude())){
query.fields().exclude(search.getExclude().split(","));
}
return query;
} /**
* 根据条件复制一个新的集合数据
* @param search
*/
// @Async("threadPoolTaskExecutor")
public void copyCollection(SearchCopy search) {
long startTime = System.currentTimeMillis();
log.info("开始把集合[{}]结果输出到另一个集合[{}]...", search.getCollName(), search.getNewId());
clearCollection(search.getNewId());
List<AggregationOperation> list = new ArrayList<>();
if(StrUtil.isNotEmpty(search.getColumns())){
list.add(Aggregation.project(search.getColumns().split(",")));
}
if(StrUtil.isNotEmpty(search.getBeginTime())){
list.add(Aggregation.match(new Criteria(MongoConstants.TIME_COLUMN).gte(Convert.toLong(search.getBeginTime()))));
}
if(StrUtil.isNotEmpty(search.getEndTime())){
list.add(Aggregation.match(new Criteria(MongoConstants.TIME_COLUMN).lte(Convert.toLong(search.getEndTime()))));
}
list.add(Aggregation.out(search.getNewId()));
Aggregation aggregation = Aggregation.newAggregation(list);
mongoTemplate.aggregateStream(aggregation, search.getCollName(), Document.class);
log.info("结果输出完成,耗时:{}秒", (System.currentTimeMillis() - startTime)/1000);
}
}

MongoTemplate增强版

使用手册:https://loser.plus/

使用MyBatisPlus的方式,优雅的操作MongoDB。

这种方式是如同Mysql表结构一样,已知集合名称和字段名称,预先定义好字段类型,自动与Mongodb进行关系映射。

SpringBoot集成Mongodb文档数据库的更多相关文章

  1. Springboot集成MongoDB存储文件、读取文件

    一.前言和开发环境及配置 可以转载,但请注明出处. 之前自己写的SpringBoot整合MongoDB的聚合查询操作,感兴趣的可以点击查阅. https://www.cnblogs.com/zaoyu ...

  2. springboot集成mongoDB 异常认证

    1.springboot连接mongoDB 出现异常认证 异常详情: com.mongodb.MongoSecurityException: Exception authenticating Mong ...

  3. SpringBoot集成MongoDB之导入导出和模板下载

    前言 自己很对自己在项目中集成MongoDb做的导入导出以及模板下载的方法总结如下,有不到之处敬请批评指正! 1.pom.xml依赖引入 <!-- excel导入导出 --> <de ...

  4. SpringBoot集成MongoDB

    前言 之前写了各种nosql数据库的比较,以及相关理论,现在我在本地以springboot+MongoDB框架,探究了具体的运行流程,下面总结一下,分享给大家. 运行前准备 安装并启动MongoDB应 ...

  5. springboot 集成mongodb

    环境依赖 在pom文件引入spring-boot-starter-data-mongodb依赖: <dependency> <groupId>org.springframewo ...

  6. SpringBoot 集成mongodb(1)单数据源配置

    新项目要用到mongodb,于是在个人电脑上的虚拟环境linux上安装了下mongodb,练习熟悉下. 1.虚拟机上启动mongodb. 首先查看虚拟机ip地址,忘了哈~~ 命令行>ifconf ...

  7. springboot集成mongoDB简易使用

    1.首先是添加Spring Data mongo的配置依赖 <dependency> <groupId>org.springframework.boot</groupId ...

  8. Springboot集成MongoDB实现CRUD

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  9. springboot集成mongoDB需要认证

    报错: Mon Nov 25 01:09:48 CST 2019 There was an unexpected error (type=Internal Server Error, status=5 ...

  10. SpringBoot 集成mongodb(2)多数据源配置

    github:https://github.com/xiaozhuanfeng/mongoProj 现MongoDB有两个数据库: pom.xml: <!-- mongodb 配置 --> ...

随机推荐

  1. WordPress 整合Bootstrap制作分页代码

    1.整合Bootstrap分页代码 * 因为wordpress默认仅仅提供简单分页, 所以要实现数字分页,需要自定义函数,wordpress可以结合bootstrap制作分页,bootstrap提供了 ...

  2. Ajax 请求总共有八种 Callback

    1)onSuccess 2)onFailure 3)onUninitialized 4)onLoading 5)onLoaded 6)onInteractive 7)onComplete 8)onEx ...

  3. Splashtop 扩展了所有 Android 8.0 以上设备的远程控制功能

    好消息:Splashtop远程访问和远程支持软件现在支持100多个品牌的 Android 设备. 2020年9月15日,远程访问和远程支持解决方案的全球领导者 Splashtop Inc. 宣布:所有 ...

  4. Go-Zero定义API实战:探索API语法规范与最佳实践(五)

    前言 上一篇文章带你实现了Go-Zero模板定制化,本文将继续分享如何使用GO-ZERO进行业务开发. 通过编写API层,我们能够对外进行接口的暴露,因此学习规范的API层编写姿势是很重要的. 通过本 ...

  5. IPv6 — 综合组网技术

    目录 文章目录 目录 前文列表 IPv4v6 综合组网技术(转换机制) 双栈策略 隧道策略 前文列表 <IPv6 - 网际协议第 6 版> <IPv6 - 地址格式与寻址模式> ...

  6. js 数组按指定字段转map-list结构

    js 数组按指定字段转map-list结构 背景介绍 在开发过程中经常会出现接口返回整个数组,我们需要将数组进行二次处理,如下格式按照不同功能模块(type)进行数据拆分 原始数据 const lis ...

  7. 机器学习策略篇:详解可避免偏差(Avoidable bias)

    可避免偏差 如果希望学习算法能在训练集上表现良好,但有时实际上并不想做得太好.得知道人类水平的表现是怎样的,可以确切告诉算法在训练集上的表现到底应该有多好,或者有多不好,让我说明是什么意思吧. 经常使 ...

  8. 不使用循环语句用if和else实现循环

    如果不使用循环语句,可以使用递归函数来实现循环的效果.递归函数是指在函数内部调用自身的函数.下面是一个使用递归函数来实现循环的示例: (初学者记得写include,这里是个普通函数,所以我没写) de ...

  9. 《剑指offer - 题目1》

    题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数 ...

  10. ARM汇编基础

    1 GNU语法 1.1 GNU汇编 GNU 汇编语法适用于所有的架构,并不是 ARM 独享的,GNU 汇编由一系列的语句组成,每行一条语句,每条语句有三个可选部分,如下: label: instruc ...