我们在使用mongo DB数据库进行查询的时候,只使用MongoRepository进行查询,实现部分复杂的查询的时候会变得有些吃力。我们可以使用MongoTemplate实现比较复杂的查询。
首先需要配置maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置简单的application.properties文件
spring.data.mongodb.uri=mongodb://yin:yin@localhost:27017
spring.data.mongodb.database=xc_cms
这是事先准备好的数据
下面对部分常用命令进行演示
@Autowired
MongoTemplate mongoTemplate;
@Override
public JsonVO testMongoFind() {
JsonVO jsonVO = new JsonVO(200, "success");
//返回只返回某些字段
Query query4 = new Query();
query4.fields().include("valueInt").include("valueInt2");
List<MongoTestEntity> entityList2 = mongoTemplate.find(query4, MongoTestEntity.class, "mongoTest");
System.out.println(entityList2);
//返回mongno不为null 或者 ""
Query query5 = new Query();
List<String> testLst = new ArrayList<>();
testLst.add("");
testLst.add(null);
query5.addCriteria(Criteria.where("valueStr").nin(testLst));
List<MongoTestEntity> entityList3 = mongoTemplate.find(query5, MongoTestEntity.class, "mongoTest");
System.out.println(entityList3);
//模糊查询
Query query6 = new Query();
//如果有特殊符号使用转义符
query6.addCriteria(Criteria.where("valueStr").regex(".*?" +"hao"+ ".*"));
List<MongoTestEntity> entityList4 = mongoTemplate.find(query6, MongoTestEntity.class, "mongoTest");
System.out.println(entityList4);
//分页排序
int pageNum = 2;
int pageSize = 3;
int start = (pageNum - 1) * pageSize;
Query query = new Query();
query.with(Sort.by(Sort.Direction.DESC, "valueInt"));
query.skip(start).limit(pageSize);
List<MongoTestEntity> entityList = mongoTemplate.find(query, MongoTestEntity.class, "mongoTest");
//计算总数
long mongoTestNum = mongoTemplate.count(query, MongoTestEntity.class, "mongoTest");
System.out.println(mongoTestNum);
//复杂sql的转化(in/and/or/大于/小于/等于)
//select * from mongoTest where valueStr in ("nihao","dajiahao")
// and valueInt>=2 and (valueInt2 =15 or time>= (now -interval 5 day))
Query query2 = new Query();
Criteria criteria =new Criteria();
List<String> valueStrParam = new ArrayList<>();
valueStrParam.add("nihao");
valueStrParam.add("dajiahao");
criteria.and("valueStr").in(valueStrParam).andOperator(Criteria.where("valueInt").gte(2)).
orOperator(Criteria.where("valueInt2").is(15), Criteria.where("time")
.gte(LocalDateTime.now().minus(5, ChronoUnit.DAYS)));
query2.addCriteria(criteria);
List<MongoTestEntity> entityList1 = mongoTemplate.find(query2, MongoTestEntity.class, "mongoTest");
System.out.println(entityList1);
//进行聚合操作 select count(valueStr) as count,valueStr as valueStr ,sum(valueInt2) as valueInt2 from mongoTest group by valueStr
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group("valueStr").count().as("count").
first("valueStr").as("valueStr").sum("valueInt2").as("valueInt2"))
///Aggregation.newAggregationOptions().allowDiskUse(true)是用来解除mongodb 查询数据默认占用最大内存的(默认100M).不然会抛出异常:
.withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
AggregationResults<AggregationVO> aggregateFrist = mongoTemplate.aggregate(aggregation, "mongoTest", AggregationVO.class);
List<AggregationVO> mappedResults = aggregateFrist.getMappedResults();
System.out.println(mappedResults);
jsonVO.setData(entityList);
return jsonVO;
用mongoTemplate做更改
@Override
public JsonVO upsetMongoTest(MongoTestEntity mongoTestEntity){
String result = "";
String str = mongoTestEntity.getValueStr();
Query query = new Query();
query.addCriteria(Criteria.where("valueStr").is(str));
org.bson.Document document = new org.bson.Document();
mongoTemplate.getConverter().write(mongoTestEntity,document);
Update update = Update.fromDocument(document);
UpdateResult upsert = mongoTemplate.upsert(query, update, MongoTestEntity.class, "mongoTest2");
if (upsert.getMatchedCount() > 0) {
System.out.println("--------------:数据更改");
result = "数据更改";
}else {
System.out.println("-----------:数据插入");
result = "数据插入";
return new JsonVO(200, "success", result);
采用另外一种方式来查询更改
* 测试查询更改
@Override
public void testUpdate() {
int pageNum = 1;
int pageSize = 10;
Sort sort = Sort.by(Sort.Direction.DESC, "valueInt");
PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
Query query = new Query();
query.addCriteria(createCriteria());
List<MongoTestEntity> mongoTest = mongoTemplate.find(query.with(pageRequest), MongoTestEntity.class, "mongoTest");
System.out.println(mongoTest);
Update update = new Update();
update.set("valueStr2", "haohao");
update.set("time", LocalDateTime.now());
Query query2 = new Query();
query2.addCriteria(createCriteria());
mongoTemplate.updateMulti(query2, update, "mongoTest");
* 添加条件
* @return
private Criteria createCriteria(){
Criteria criteria = new Criteria();
ArrayList<String> valueStrLst = new ArrayList<>();
valueStrLst.add("nihao");
valueStrLst.add("wohao");
criteria.and("valueStr").in(valueStrLst);
criteria.and("valueStr2").is("wohao");
return criteria;
附上使用的vo类
@Data
public class MongoTestEntity {
private String id;
private Integer valueInt;
private Integer valueInt2;
private String valueStr;
private LocalDateTime time;
@Data
public class AggregationVO {
private String valueStr;
private Integer count;
private Integer valueInt2;
附上使用插入数据的代码
@Override
public JsonVO insertData(){
JsonVO jsonVO = new JsonVO(200, "success");
List<MongoTestEntity> entityList = new ArrayList<>();
MongoTestEntity mongoTestEntity = new MongoTestEntity();
mongoTestEntity.setValueInt(1);
mongoTestEntity.setValueInt2(11);
mongoTestEntity.setValueStr("nihao");
mongoTestEntity.setTime( LocalDateTime.now().minus(10, ChronoUnit.HOURS));
entityList.add(mongoTestEntity);
MongoTestEntity mongoTestEntity2 = new MongoTestEntity();
mongoTestEntity2.setValueInt(1);
mongoTestEntity2.setValueInt2(15);
mongoTestEntity2.setValueStr("wohao");
mongoTestEntity2.setTime( LocalDateTime.now().minus(15, ChronoUnit.HOURS));
entityList.add(mongoTestEntity2);
MongoTestEntity mongoTestEntity3 = new MongoTestEntity();
mongoTestEntity3.setValueInt(5);
mongoTestEntity3.setValueInt2(15);
mongoTestEntity3.setValueStr("dajiahao");
mongoTestEntity3.setTime( LocalDateTime.now().minus(5, ChronoUnit.HOURS));
entityList.add(mongoTestEntity3);
MongoTestEntity mongoTestEntity4 = new MongoTestEntity();
mongoTestEntity4.setValueInt(5);
mongoTestEntity4.setValueInt2(15);
mongoTestEntity4.setTime( LocalDateTime.now().minus(5, ChronoUnit.HOURS));
entityList.add(mongoTestEntity4);
mongoTemplate.insert(entityList, "mongoTest");
return jsonVO;
我们在使用mongo DB数据库进行查询的时候,只使用MongoRepository进行查询,实现部分复杂的查询的时候会变得有些吃力。我们可以使用MongoTemplate实现比较复杂的查询。首先需要配置maven依赖 <dependency> <groupId>org.springframework.boot</groupId> ...
SpringData MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate对MongoDB的find的操作,我们上一篇介绍了基本文档的查询,我们今天介绍分页查询,分页查询是返回到匹配文档的游标,可以随意修改查询限制、跳跃、和排序顺序的功能。
我们在查询时find()方法接受Query类型...
{$and : [{ARV_APT: "PEK"}, {$and: [{FLT_DATE: {$gte: "20180101"}}, {FLT_DATE: {$lte: "20180104"}}]}]}
然后传给后端进行查询,将结果返回。
之前使用mongodb进行CRUD的时候都是基于API的
1:使用...
public void specialFieldQuery() {
Query query = new Query(Criteria.where("user").is("用户名blog"));
// 查询一条满足条件的数据
Map result = mongoTemplate.findOne(query, Map.class
参数说明:sql(Operators)
where ($match) 、group by ($group)、having($match)、select($project)、order by($sort)、limit($limit)
sum($sum)、count($sum)、join($lookup)
* project:列出所有本次查询的字段,包括查询条件的字段和需要搜索的字段;
* match:搜索条件criteria
* un...
@Document("Schedule")
@Accessors(chain = true)
public class Schedule extends BaseMongoEntity {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "医院编号")
@Indexed //.
使用 Spring Data MongoDB时,我们可能需要限制从数据库对象映射的属性。通常,出于安全原因,我们可能需要这样做—以避免暴露存储在服务器上的敏感信息。或者,例如,我们可能需要过滤掉 Web 应用程序中显示的部分数据。
在这个简短的教程中,我们将看到 MongoDB 如何应用字段限制。
@Repository
public interface MsgRecordRepository extends MongoRepository<MsgCollection, String> {
@Query(fields = "{'message.msgId' : 1,'message.templateTypeId' : 1,'message.msgType' : 1,'...
query.addCriteria(new Criteria()
.andOperator(criteria, new Criteria()
.orOperator(Criteria.where(BatteryRealtimeInfo.BatteryRealtimeInfoEnum.updateTime.name())
.lt(LocalDateTime.ofInstant(Instant.ofEpochMilli(now -.
```java
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
public class AggregationExample {
private MongoTemplate mongoTemplate;
public AggregationExample(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
public void performAggregation() {
TypedAggregation aggregation = newAggregation(
// 添加聚合操作
match(Criteria.where("fieldName").is("value")),
group("groupField").count().as("count"),
sort(Sort.Direction.DESC, "count")
AggregationResults<AggregateResultClass> results = mongoTemplate.aggregate(aggregation, "collectionName", AggregateResultClass.class);
List<AggregateResultClass> resultList = results.getMappedResults();
// 处理结果
for (AggregateResultClass result : resultList) {
// 进行相应的操作
// result.getGroupField();
// result.getCount();
// 聚合结果的POJO类
class AggregateResultClass {
private String groupField;
private int count;
// 省略构造函数、getter和setter
请根据您的具体需求修改上述示例中的字段和条件。希望对您有所帮助!如果您有任何其他问题,请随时提问。
//输出list
System.out.println("list:"+list);
System.out.println("arrays:"+list.getClass().getSimpleName());
批量删除时用得到,不用谢
k8s Master节点和Node节点上各组件和核心概念的介绍
远方 hi: