1、MongoClient

依赖jar包

  1. <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
  2. <!--包含 the legacy driver, the mongodb-driver, mongodb-driver-core, and bson-->
  3. <!--版本对应4.0.0,超过9进一。如3.11.0,对应4.1.0-->
  4. <dependency>
  5. <groupId>org.mongodb</groupId>
  6. <artifactId>mongo-java-driver</artifactId>
  7. <version>3.10.0</version>
  8. </dependency>
  1. MongoClient mongoClient = new MongoClient("192.168.189.100", 40000);
  2. ArrayList<ServerAddress> serverAddresses = new ArrayList<>();
  3. serverAddresses.add(new ServerAddress("192.168.189.100", 27018));
  4. serverAddresses.add(new ServerAddress("192.168.189.101", 27018));
  5. serverAddresses.add(new ServerAddress("192.168.189.102", 27018));
  6. MongoClient mongoClient1 = new MongoClient(serverAddresses);
  7. MongoDatabase demo = mongoClient.getDatabase("demo");
  8. MongoCollection<Document> books = demo.getCollection("books");
  9. Document document = new Document()
  10. .append("title", "MongoDB Insert Demo")
  11. .append("description","database")
  12. .append("likes", 30)
  13. .append("by", "demo point")
  14. .append("url", "http://c.biancheng.net/mongodb/");
  15. books.insertOne(document);
  16. DeleteResult deleteResult = books.deleteMany(new Document("name", "php"));
  17. System.out.println(deleteResult.getDeletedCount());
  18. FindIterable<Document> documents = books.find();
  19. for (Document document1 : documents) {
  20. System.out.println(document1);
  21. }

2、与springboot整合

参考
配置

  1. package com.sgcc.dlsc.diagnosis.dao;
  2. import com.mongodb.BasicDBObject;
  3. import com.mongodb.DuplicateKeyException;
  4. import com.mongodb.MongoWriteException;
  5. import com.mongodb.client.result.DeleteResult;
  6. import com.mongodb.client.result.UpdateResult;
  7. import com.sgcc.dlsc.diagnosis.model.po.DiagnosisStrategy;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.data.mongodb.core.MongoTemplate;
  10. import org.springframework.data.mongodb.core.query.Criteria;
  11. import org.springframework.data.mongodb.core.query.Query;
  12. import org.springframework.data.mongodb.core.query.Update;
  13. import org.springframework.stereotype.Repository;
  14. import java.util.ArrayList;
  15. import java.util.LinkedHashMap;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.stream.Collectors;
  19. /**
  20. * @Author: 李孟帅
  21. * @CreateTime: 2020-06-03 13:46
  22. * @Description:
  23. */
  24. @Repository
  25. public class DiagnosisStrategyMongoDao {
  26. @Autowired
  27. private MongoTemplate mongoTemplate;
  28. public List<String> findAllNames() {
  29. Query query = new Query();
  30. query.fields().include("serviceName");
  31. List<DiagnosisStrategy> diagnosisStrategies = mongoTemplate.find(query, DiagnosisStrategy.class);
  32. ArrayList<String> serviceNames = diagnosisStrategies.stream().map(DiagnosisStrategy::getServiceName).collect(Collectors.toCollection(ArrayList::new));
  33. return serviceNames;
  34. }
  35. public Map findAll(int page, int size) {
  36. Query query = new Query();
  37. long count = mongoTemplate.count(query, DiagnosisStrategy.class);
  38. query.skip((page - 1) * size).limit(size);
  39. List<DiagnosisStrategy> diagnosisStrategies = mongoTemplate.find(query, DiagnosisStrategy.class);
  40. Map<Object, Object> map = new LinkedHashMap<>(2);
  41. map.put("total",count);
  42. map.put("strategies",diagnosisStrategies);
  43. return map;
  44. }
  45. public DiagnosisStrategy findByName(String serviceName) {
  46. Query query = new Query(Criteria.where("serviceName").is(serviceName));
  47. DiagnosisStrategy one = mongoTemplate.findOne(query, DiagnosisStrategy.class);
  48. Map<Object, Object> map = new LinkedHashMap<>(2);
  49. return one;
  50. }
  51. public DiagnosisStrategy save(DiagnosisStrategy diagnosisStrategy) {
  52. DiagnosisStrategy result=null;
  53. try {
  54. result = mongoTemplate.save(diagnosisStrategy);
  55. }catch (Exception e){
  56. System.out.println("插入的服务名重复:"+e.getMessage());
  57. }
  58. return result;
  59. }
  60. public Long remove(String id) {
  61. Query query = new Query(Criteria.where("_id").is(id));
  62. DeleteResult remove = mongoTemplate.remove(query, DiagnosisStrategy.class);
  63. return remove.getDeletedCount();
  64. }
  65. public Long update(DiagnosisStrategy diagnosisStrategy) {
  66. Query query = new Query(Criteria.where("_id").is(diagnosisStrategy.getId()));
  67. Update update = new Update();
  68. update.set("endpoints", diagnosisStrategy.getEndpoints());
  69. UpdateResult updateResult = mongoTemplate.updateFirst(query, update, DiagnosisStrategy.class);
  70. return updateResult.getModifiedCount();
  71. }
  72. }
  1. public Map findByName(String serviceName, long start, long end, int page, int size) {
  2. Query query = new Query();
  3. //查询指定的服务,在一段时间之内的诊断结果
  4. Criteria criteria = Criteria.where("serviceName").is(serviceName).and("timestamp").gte(start).lte(end).and("instances.diagnosisInfo").exists(true);
  5. //总数
  6. long count = mongoTemplate.count(query.addCriteria(criteria), Service.class);
  7. //排序,分页
  8. query.with(new Sort(Sort.Direction.DESC, "timestamp")).skip((page - 1) * size).limit(size);
  9. //查询
  10. List<Service> result = mongoTemplate.find(query, Service.class);
  11. Map<String, Object> hashMap = new LinkedHashMap<>();
  12. hashMap.put("total", count);
  13. hashMap.put("result", result);
  14. return hashMap;
  15. }

2.1、查询

  1. db.diagnosisResult.find(
  2. {
  3. "serviceName":"px-basesystem-diagnosis","timestamp":{$gte:1591174741099,$lte:1591232840255}
  4. }
  5. ).limit(60)
  1. public List<Service> findByName(String serviceName,long start,long end) {
  2. Query query = new Query();
  3. Criteria criteria = Criteria.where("serviceName").is(serviceName).and("timestamp").gte(start).lte(end);
  4. query.addCriteria(criteria).with(new Sort(Sort.Direction.DESC, "timestamp")).limit(60);
  5. List<Service> diagnosisStrategies = mongoTemplate.find(query, Service.class);
  6. return diagnosisStrategies;
  7. }

2.2、聚会

  1. db.diagnosisResult.aggregate(
  2. [
  3. {
  4. $group: {
  5. _id: "$serviceName",
  6. "serviceName": {
  7. $first: "$serviceName"
  8. },
  9. "instances": {
  10. $first: "$instances"
  11. },
  12. "id": {
  13. $first: "$_id"
  14. },
  15. timestamp: {
  16. $max: "$timestamp"
  17. }
  18. }
  19. },
  20. {
  21. $project: {
  22. "_id": 0
  23. }
  24. },
  25. {
  26. $sort: {
  27. "serviceName": 1
  28. }
  29. }
  30. ]
  31. )
  32. db.diagnosisResult.aggregate(
  33. [
  34. {
  35. $group: {
  36. _id: "$serviceName",
  37. "serviceName": {
  38. $first: "$serviceName"
  39. },
  40. "instances": {
  41. $first: "$instances"
  42. },
  43. "id": {
  44. $first: "$_id"
  45. },
  46. timestamp: {
  47. $max: "$timestamp"
  48. }
  49. }
  50. },{$project:{"_id": 0 }},{$match:{"serviceName":/com/}},{$sort: {"serviceName":1}
  51. },{$limit:2},{$skip:0}
  52. ]
  53. )
  1. public List<Service> findAll() {
  2. Query query = new Query();
  3. Aggregation aggregation = Aggregation.newAggregation(
  4. Aggregation.project("_id", "serviceName", "instances", "timestamp"),
  5. Aggregation.group("serviceName").first("serviceName").as("serviceName")
  6. .first("instances").as("instances").first("_id").as("id").max("timestamp").as("timestamp"),
  7. Aggregation.project("id","serviceName","instances","timestamp").andExclude("_id"),
  8. Aggregation.sort(Sort.Direction.ASC, "serviceName")
  9. );
  10. AggregationResults<Service> diagnosisResult = mongoTemplate.aggregate(aggregation, "diagnosisResult", Service.class);
  11. List<Service> mappedResults = diagnosisResult.getMappedResults();
  12. System.out.println(mappedResults);
  13. return mappedResults;
  14. }