经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MongoDB » 查看文章
SpringBoot集成Mongodb文档数据库
来源:cnblogs  作者:zhαojh  时间:2024/7/8 10:19:13  对本文有异议

添加Maven依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  4. </dependency>

配置Mongodb连接信息

  1. spring:
  2. data:
  3. mongodb:
  4. host: 10.30.29.246
  5. port: 16030
  6. authenticationDatabase: admin # 登录用户的认证库
  7. database: nrdt
  8. username: admin
  9. password: QAZqaz@123321

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

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

  1. @Slf4j
  2. @Component
  3. public class MongodbService {
  4. @Autowired
  5. private MongoTemplate mongoTemplate;
  6. /**
  7. * 新增集合(表)
  8. *
  9. * @param collName
  10. */
  11. public void addCollection(String collName) {
  12. Assert.notEmpty(collName, "collName");
  13. boolean bol = mongoTemplate.collectionExists(collName);
  14. if (!bol) {
  15. mongoTemplate.createCollection(collName);
  16. }
  17. }
  18. /**
  19. * 删除集合(表)
  20. *
  21. * @param collName
  22. */
  23. public void dropCollection(String collName) {
  24. Assert.notEmpty(collName, "collName");
  25. boolean bol = mongoTemplate.collectionExists(collName);
  26. if (bol) {
  27. mongoTemplate.dropCollection(collName);
  28. }
  29. }
  30. /**
  31. * 清空集合数据
  32. *
  33. * @param collName
  34. */
  35. public void clearCollection(String collName) {
  36. Assert.notEmpty(collName, "collName");
  37. boolean bol = mongoTemplate.collectionExists(collName);
  38. if (bol) {
  39. mongoTemplate.remove(new Query(), collName);
  40. }
  41. }
  42. /**
  43. * 修改字段名称
  44. *
  45. * @param collName
  46. * @param oldName
  47. * @param newName
  48. * @return
  49. */
  50. public boolean editField(String collName, String oldName, String newName) {
  51. Assert.notEmpty(collName, "collName");
  52. Assert.notEmpty(oldName, "oldName");
  53. Assert.notEmpty(newName, "newName");
  54. Query query = new Query();
  55. Update update = new Update();
  56. update.rename(oldName, newName);
  57. UpdateResult result = mongoTemplate.updateMulti(query, update, collName);
  58. return result.wasAcknowledged();
  59. }
  60. /**
  61. * 删除指定列
  62. *
  63. * @param collName
  64. * @param field
  65. */
  66. public boolean dropField(String collName, String field) {
  67. Assert.notEmpty(collName, "collName");
  68. Assert.notEmpty(field, "field");
  69. Query query = new Query();
  70. Update update = new Update();
  71. update.unset(field);
  72. UpdateResult result = mongoTemplate.updateMulti(query, update, collName);
  73. return result.wasAcknowledged();
  74. }
  75. /**
  76. * 新增字段
  77. *
  78. * @param collName
  79. * @param field
  80. * @return
  81. */
  82. public boolean addField(String collName, String field) {
  83. Assert.notEmpty(collName, "collName");
  84. Assert.notEmpty(field, "field");
  85. Query query = new Query();
  86. query.fields().include(field);
  87. boolean bol = mongoTemplate.exists(query, collName);
  88. if(!bol){
  89. Update update = new Update();
  90. update.set(field, 0.00d);
  91. UpdateResult result = mongoTemplate.updateMulti(query, update, collName);
  92. return result.wasAcknowledged();
  93. }
  94. return false;
  95. }
  96. /**
  97. * 新增多个字段
  98. *
  99. * @param collName
  100. * @param fields
  101. * @return
  102. */
  103. public boolean addFields(String collName, List<String> fields) {
  104. Assert.notEmpty(collName, "collName");
  105. Assert.notNull(fields, "fields");
  106. Update update = new Update();
  107. boolean status = false;
  108. for (String field : fields) {
  109. Query query = new Query();
  110. query.fields().include(field);
  111. boolean bol = mongoTemplate.exists(query, collName);
  112. if(!bol){
  113. update.set(field, 0.00d);
  114. status = true;
  115. }
  116. }
  117. if(status){
  118. UpdateResult result = mongoTemplate.updateMulti(new Query(), update, collName);
  119. return result.wasAcknowledged();
  120. } else {
  121. return false;
  122. }
  123. }
  124. /**
  125. * 批量新增行数据
  126. *
  127. * @param collName
  128. * @param jsonArray
  129. */
  130. public void insert(String collName, JSONArray jsonArray) {
  131. Assert.notEmpty(collName, "collName");
  132. Assert.notNull(jsonArray, "jsonArray");
  133. mongoTemplate.insert(jsonArray, collName);
  134. }
  135. /**
  136. * 批量插入
  137. * insert: 可以一次性插入一整个列表,不允许插入已存在的主键
  138. * save: 需要遍历列表,进行一条一条的数据插入,主键存在则是修改
  139. * @param collName
  140. * @param list
  141. */
  142. public void insert(String collName, List<Document> list) {
  143. Assert.notEmpty(collName, "collName");
  144. Assert.notNull(list, "list");
  145. mongoTemplate.insert(list, collName);
  146. }
  147. /**
  148. * 修改行数据
  149. *
  150. * @param collName
  151. */
  152. public void edit(String collName, JSONObject jsonObject) {
  153. Assert.notEmpty(collName, "collName");
  154. Assert.notNull(jsonObject, "jsonObject");
  155. mongoTemplate.save(jsonObject, collName);
  156. }
  157. /**
  158. * 删除行数据
  159. *
  160. * @param collName
  161. */
  162. public boolean remove(String collName, String[] ids) {
  163. Assert.notEmpty(collName, "collName");
  164. Assert.notNull(ids, "ids");
  165. Query query = new Query(Criteria.where(MongoConstants.ID_COLUMN).in(ids));
  166. DeleteResult result = mongoTemplate.remove(query, collName);
  167. return result.wasAcknowledged();
  168. }
  169. /**
  170. * 抽样查询
  171. * @param search
  172. * @return
  173. */
  174. public List<Document> getListSample(SearchVo search){
  175. List<AggregationOperation> list = new ArrayList<>();
  176. list.add(Aggregation.sample(search.getSampleSize()));
  177. if(StrUtil.isNotEmpty(search.getColumns())){
  178. list.add(Aggregation.project(search.getColumns().split(",")));
  179. }
  180. Aggregation aggregation = Aggregation.newAggregation(list);
  181. return mongoTemplate.aggregate(aggregation, search.getCollName(), Document.class).getMappedResults();
  182. }
  183. /**
  184. * 查询样本时间的上下限
  185. * @param collName
  186. * @return
  187. */
  188. public Map<String, Object> getTimes(String collName){
  189. long startTime = System.currentTimeMillis();
  190. Map<String, Object> map = new HashMap<>();
  191. Assert.notEmpty(collName, "collName");
  192. List<AggregationOperation> list = new ArrayList<>();
  193. list.add(Aggregation.project(MongoConstants.TIME_COLUMN));
  194. list.add(Aggregation.group().min(MongoConstants.TIME_COLUMN).as("minTime").max(MongoConstants.TIME_COLUMN).as("maxTime"));
  195. Aggregation aggregation = Aggregation.newAggregation(list);
  196. Document doc = mongoTemplate.aggregate(aggregation, collName, Document.class).getRawResults();
  197. if(doc != null){
  198. if(Convert.toInt(doc.get("ok")) == 1){
  199. List<Document> results = doc.get("results", List.class);
  200. if(results != null && results.size() > 0){
  201. Document obj = results.get(0);
  202. if(obj != null){
  203. map.put("minTime", obj.getLong("minTime"));
  204. map.put("maxTime", obj.getLong("maxTime"));
  205. }
  206. }
  207. }
  208. }
  209. if(CollUtil.isEmpty(map)){
  210. map.put("minTime", null);
  211. map.put("maxTime", null);
  212. }
  213. log.info("查询样本上下限时间,耗时:{}秒", (System.currentTimeMillis() - startTime)/1000);
  214. return map;
  215. }
  216. /**
  217. * 分页查询表数据
  218. *
  219. * @param search
  220. * @return
  221. */
  222. public TableDataInfo getPage(SearchInput search) {
  223. List<JSONObject> list = new ArrayList<>();
  224. Query query = getQuery(search);
  225. long count = mongoTemplate.count(query, search.getCollName());
  226. if (count > 0L) {
  227. if (StrUtil.isEmpty(search.getSort())) {
  228. // 默认根据时间排序
  229. search.setSort(MongoConstants.TIME_COLUMN);
  230. }
  231. // 分页:跳过前skip个文档,返回接下来的pageSize个文档
  232. int skip = (search.getPageNum() - 1) * search.getPageSize();
  233. query = query.with(Sort.by(search.getSort()).ascending()).skip(skip).limit(search.getPageSize());
  234. list = mongoTemplate.find(query, JSONObject.class, search.getCollName());
  235. }
  236. TableDataInfo rspData = new TableDataInfo();
  237. rspData.setCode(HttpStatus.SUCCESS);
  238. rspData.setRows(list);
  239. rspData.setMsg("查询成功");
  240. rspData.setTotal(count);
  241. return rspData;
  242. }
  243. /**
  244. * 根据条件查询数据量
  245. *
  246. * @param search
  247. * @return
  248. */
  249. public long getCount(SearchInput search) {
  250. Query query = getQuery(search);
  251. return mongoTemplate.count(query, search.getCollName());
  252. }
  253. /**
  254. * 分页查询集合的数据
  255. *
  256. * @param search
  257. * @return
  258. */
  259. public List<Document> getListDoc(SearchInput search) {
  260. Query query = getQuery(search);
  261. if (StrUtil.isNotEmpty(search.getSort())) {
  262. query = query.with(Sort.by(search.getSort()).ascending());
  263. }
  264. int skip = (search.getPageNum() - 1) * search.getPageSize();
  265. query = query.skip(skip).limit(search.getPageSize());
  266. return mongoTemplate.find(query, Document.class , search.getCollName());
  267. }
  268. /**
  269. * 随机查询一条数据
  270. * @param collName
  271. * @return
  272. */
  273. public JSONObject getOne(String collName){
  274. Query query = new Query();
  275. query = query.limit(1);
  276. return mongoTemplate.findOne(query, JSONObject.class, collName);
  277. }
  278. public Query getQuery(SearchInput search) {
  279. Criteria criteria = new Criteria();
  280. List<Criteria> criteriaList = new ArrayList<>();
  281. if (StrUtil.isNotEmpty(search.getBeginTime())) {
  282. criteriaList.add(Criteria.where(MongoConstants.TIME_COLUMN).gte(Convert.toLong(search.getBeginTime())));
  283. }
  284. if (StrUtil.isNotEmpty(search.getEndTime())) {
  285. criteriaList.add(Criteria.where(MongoConstants.TIME_COLUMN).lte(Convert.toLong(search.getEndTime())));
  286. }
  287. if (criteriaList.size() > 0) {
  288. criteria.andOperator(criteriaList);
  289. }
  290. Query query = new Query(criteria);
  291. if (StrUtil.isNotEmpty(search.getColumns())) {
  292. query.fields().include(search.getColumns().split(","));
  293. }
  294. if(StrUtil.isNotEmpty(search.getExclude())){
  295. query.fields().exclude(search.getExclude().split(","));
  296. }
  297. return query;
  298. }
  299. /**
  300. * 根据条件复制一个新的集合数据
  301. * @param search
  302. */
  303. // @Async("threadPoolTaskExecutor")
  304. public void copyCollection(SearchCopy search) {
  305. long startTime = System.currentTimeMillis();
  306. log.info("开始把集合[{}]结果输出到另一个集合[{}]...", search.getCollName(), search.getNewId());
  307. clearCollection(search.getNewId());
  308. List<AggregationOperation> list = new ArrayList<>();
  309. if(StrUtil.isNotEmpty(search.getColumns())){
  310. list.add(Aggregation.project(search.getColumns().split(",")));
  311. }
  312. if(StrUtil.isNotEmpty(search.getBeginTime())){
  313. list.add(Aggregation.match(new Criteria(MongoConstants.TIME_COLUMN).gte(Convert.toLong(search.getBeginTime()))));
  314. }
  315. if(StrUtil.isNotEmpty(search.getEndTime())){
  316. list.add(Aggregation.match(new Criteria(MongoConstants.TIME_COLUMN).lte(Convert.toLong(search.getEndTime()))));
  317. }
  318. list.add(Aggregation.out(search.getNewId()));
  319. Aggregation aggregation = Aggregation.newAggregation(list);
  320. mongoTemplate.aggregateStream(aggregation, search.getCollName(), Document.class);
  321. log.info("结果输出完成,耗时:{}秒", (System.currentTimeMillis() - startTime)/1000);
  322. }
  323. }

MongoTemplate增强版

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

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

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

原文链接:https://www.cnblogs.com/zhaojinhui/p/18289404

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号