1、MongoClient
依赖jar包
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<!--包含 the legacy driver, the mongodb-driver, mongodb-driver-core, and bson-->
<!--版本对应4.0.0,超过9进一。如3.11.0,对应4.1.0-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.0</version>
</dependency>
MongoClient mongoClient = new MongoClient("192.168.189.100", 40000);
ArrayList<ServerAddress> serverAddresses = new ArrayList<>();
serverAddresses.add(new ServerAddress("192.168.189.100", 27018));
serverAddresses.add(new ServerAddress("192.168.189.101", 27018));
serverAddresses.add(new ServerAddress("192.168.189.102", 27018));
MongoClient mongoClient1 = new MongoClient(serverAddresses);
MongoDatabase demo = mongoClient.getDatabase("demo");
MongoCollection<Document> books = demo.getCollection("books");
Document document = new Document()
.append("title", "MongoDB Insert Demo")
.append("description","database")
.append("likes", 30)
.append("by", "demo point")
.append("url", "http://c.biancheng.net/mongodb/");
books.insertOne(document);
DeleteResult deleteResult = books.deleteMany(new Document("name", "php"));
System.out.println(deleteResult.getDeletedCount());
FindIterable<Document> documents = books.find();
for (Document document1 : documents) {
System.out.println(document1);
}
2、与springboot整合
package com.sgcc.dlsc.diagnosis.dao;
import com.mongodb.BasicDBObject;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoWriteException;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.sgcc.dlsc.diagnosis.model.po.DiagnosisStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author: 李孟帅
* @CreateTime: 2020-06-03 13:46
* @Description:
*/
@Repository
public class DiagnosisStrategyMongoDao {
@Autowired
private MongoTemplate mongoTemplate;
public List<String> findAllNames() {
Query query = new Query();
query.fields().include("serviceName");
List<DiagnosisStrategy> diagnosisStrategies = mongoTemplate.find(query, DiagnosisStrategy.class);
ArrayList<String> serviceNames = diagnosisStrategies.stream().map(DiagnosisStrategy::getServiceName).collect(Collectors.toCollection(ArrayList::new));
return serviceNames;
}
public Map findAll(int page, int size) {
Query query = new Query();
long count = mongoTemplate.count(query, DiagnosisStrategy.class);
query.skip((page - 1) * size).limit(size);
List<DiagnosisStrategy> diagnosisStrategies = mongoTemplate.find(query, DiagnosisStrategy.class);
Map<Object, Object> map = new LinkedHashMap<>(2);
map.put("total",count);
map.put("strategies",diagnosisStrategies);
return map;
}
public DiagnosisStrategy findByName(String serviceName) {
Query query = new Query(Criteria.where("serviceName").is(serviceName));
DiagnosisStrategy one = mongoTemplate.findOne(query, DiagnosisStrategy.class);
Map<Object, Object> map = new LinkedHashMap<>(2);
return one;
}
public DiagnosisStrategy save(DiagnosisStrategy diagnosisStrategy) {
DiagnosisStrategy result=null;
try {
result = mongoTemplate.save(diagnosisStrategy);
}catch (Exception e){
System.out.println("插入的服务名重复:"+e.getMessage());
}
return result;
}
public Long remove(String id) {
Query query = new Query(Criteria.where("_id").is(id));
DeleteResult remove = mongoTemplate.remove(query, DiagnosisStrategy.class);
return remove.getDeletedCount();
}
public Long update(DiagnosisStrategy diagnosisStrategy) {
Query query = new Query(Criteria.where("_id").is(diagnosisStrategy.getId()));
Update update = new Update();
update.set("endpoints", diagnosisStrategy.getEndpoints());
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, DiagnosisStrategy.class);
return updateResult.getModifiedCount();
}
}
public Map findByName(String serviceName, long start, long end, int page, int size) {
Query query = new Query();
//查询指定的服务,在一段时间之内的诊断结果
Criteria criteria = Criteria.where("serviceName").is(serviceName).and("timestamp").gte(start).lte(end).and("instances.diagnosisInfo").exists(true);
//总数
long count = mongoTemplate.count(query.addCriteria(criteria), Service.class);
//排序,分页
query.with(new Sort(Sort.Direction.DESC, "timestamp")).skip((page - 1) * size).limit(size);
//查询
List<Service> result = mongoTemplate.find(query, Service.class);
Map<String, Object> hashMap = new LinkedHashMap<>();
hashMap.put("total", count);
hashMap.put("result", result);
return hashMap;
}
2.1、查询
db.diagnosisResult.find(
{
"serviceName":"px-basesystem-diagnosis","timestamp":{$gte:1591174741099,$lte:1591232840255}
}
).limit(60)
public List<Service> findByName(String serviceName,long start,long end) {
Query query = new Query();
Criteria criteria = Criteria.where("serviceName").is(serviceName).and("timestamp").gte(start).lte(end);
query.addCriteria(criteria).with(new Sort(Sort.Direction.DESC, "timestamp")).limit(60);
List<Service> diagnosisStrategies = mongoTemplate.find(query, Service.class);
return diagnosisStrategies;
}
2.2、聚会
db.diagnosisResult.aggregate(
[
{
$group: {
_id: "$serviceName",
"serviceName": {
$first: "$serviceName"
},
"instances": {
$first: "$instances"
},
"id": {
$first: "$_id"
},
timestamp: {
$max: "$timestamp"
}
}
},
{
$project: {
"_id": 0
}
},
{
$sort: {
"serviceName": 1
}
}
]
)
db.diagnosisResult.aggregate(
[
{
$group: {
_id: "$serviceName",
"serviceName": {
$first: "$serviceName"
},
"instances": {
$first: "$instances"
},
"id": {
$first: "$_id"
},
timestamp: {
$max: "$timestamp"
}
}
},{$project:{"_id": 0 }},{$match:{"serviceName":/com/}},{$sort: {"serviceName":1}
},{$limit:2},{$skip:0}
]
)
public List<Service> findAll() {
Query query = new Query();
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.project("_id", "serviceName", "instances", "timestamp"),
Aggregation.group("serviceName").first("serviceName").as("serviceName")
.first("instances").as("instances").first("_id").as("id").max("timestamp").as("timestamp"),
Aggregation.project("id","serviceName","instances","timestamp").andExclude("_id"),
Aggregation.sort(Sort.Direction.ASC, "serviceName")
);
AggregationResults<Service> diagnosisResult = mongoTemplate.aggregate(aggregation, "diagnosisResult", Service.class);
List<Service> mappedResults = diagnosisResult.getMappedResults();
System.out.println(mappedResults);
return mappedResults;
}