相关文章推荐
爱旅游的伤疤  ·  Python ...·  11 月前    · 
千杯不醉的跑步鞋  ·  Jupyter ...·  1 年前    · 

很多复杂的查询都是从简单的部分组合的实现,续接昨天的通过Query查询后,今天接着补充聚合管道-Aggregation 进行数据查询,处理。相比较Query查询,Aggregation 再处理数据时会方便很多,也便于优化查询语句。

首先springboot引入mongodb的配置也是从引入pom依赖->配置文件中mongodb的连接信息配置->在具体service中注入MongoTemplate 。这些上一篇文章都已经有写,不在重复。

需要注意导包是这些:org.springframework.data.mongodb.core.**;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

下面直接上demo。我这都是在单元测试中写的。

1.聚合管道实现简单的条件,排序数据查询功能。

注意点:执行 顺序可以完全参考mysql的书写顺序。

mysql是先where语句,然后排序,然后limit。

mongodb一样。也是必须先是条件语句,然后limit和sort。条件语句必须放到第一位,不然查询的可能为空。然后就是limit,sort谁在前的含义是不一样的。是先截取数据,对截取的数据排序还是先排序,在截取数据。这个也要考虑好了。正常是先排序,在截取数据。

注意点:查询结果用实体类封装。最好不用Map ,withOptions()用来解除mongodb 查询数据默认占用最大内存的(默认100M).

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private HomeworkMultimediaMapper homeworkMultimediaMapper;
@Test
public void test1() {
HomeworkMultimedia homeworkMultimedia = homeworkMultimediaMapper.selectByPrimaryKey(124L);
Criteria criteria = new Criteria();
        criteria.and("virtualClassId").is(homeworkMultimedia.getVirtualClassId()).and("classTypeId").is(homeworkMultimedia.getClassTypeId());
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.sort(Sort.Direction.ASC,"createTime","contentType"),             
                Aggregation.limit(20)
        ).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
        //withOptions()用来解除mongodb 查询数据默认占用最大内存的(默认100M).
AggregationResults homeworkMultimediaDetailDocuments = mongoTemplate.aggregate(aggregation, "homework_multimedia_detail", HomeworkMultimediaDetailDocument.class);
List mappedResults = homeworkMultimediaDetailDocuments.getMappedResults();
LOGGER.info("results:{}",JSONObject.toJSONString(mappedResults));

2.聚合管道实现分组统计功能

Aggregation.group() : 聚合函数,将某个字段或者某个数组作为分组统计的依据。单独的分组实际上没啥用,一般都是分组后接着做些具体的分组统计操作。

具体的常用分组后的方法如下:

分组查询的结果一般需要起别名,意味着字段不在查询封装的实体中,可以使用Map来接受值

查询顺序是match,group,limit。

    @Test
    public void test2() {
        Criteria criteria = new Criteria();
        criteria.and("virtualClassId").is(4832400134809422L);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("contentType").count().as("contentTypeCount"),
                Aggregation.limit(200)
        ).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
        AggregationResults homeworkMultimediaDetailDocuments = mongoTemplate.aggregate(aggregation, "homework_multimedia_detail", Map.class);
        List mappedResults = homeworkMultimediaDetailDocuments.getMappedResults();
        LOGGER.info("results:{}",JSONObject.toJSONString(mappedResults));

查询结果的数据结构是这样:results:[{"_id":1,"contentTypeCount":16},{"_id":2,"contentTypeCount":6},{"_id":3,"contentTypeCount":6}]

很多复杂的查询都是从简单的部分组合的实现,续接昨天的通过Query查询后,今天接着补充聚合管道-Aggregation进行数据查询,处理。相比较Query查询,Aggregation再处理数据时会方便很多,也便于优化查询语句。首先springboot引入mongodb的配置也是从引入pom依赖->配置文件中mongodb的连接信息配置->在具体service中注入MongoTemplate 。这些上一篇文章都已经有写,不在重复。需要注意导包是这些:org.springframewor.. Query query = new Query(); query.addCriteria(criteria); long sumCount = mongoTemplate.count(query, MaterialInfo.class); Aggregation aggregation = Aggregation.newA
使用spring data mongodb 提供的MongoTemplate 模板,进行Aggregation操作实践 public class FlowSizeAggregateTest public static void main(String[] args) throws Exception ApplicationContext context = new C
好的,我可以回答这个问题。在使用 Spring Boot 和 MongoDB 进行三表连接时,可以使用 MongoTemplate 类来实现。首先,需要定义三个实体类,分别对应三个集合。然后,使用 MongoTemplate 的 aggregate 方法进行聚合操作,通过 $lookup 和 $match 等操作实现三表连接。具体实现可以参考以下代码: @Autowired private MongoTemplate mongoTemplate; public List<ThirdTable> findThirdTableByJoin() { Aggregation aggregation = Aggregation.newAggregation( Aggregation.lookup("secondTable", "secondTableId", "id", "secondTable"), Aggregation.unwind("secondTable"), Aggregation.lookup("firstTable", "secondTable.firstTableId", "id", "firstTable"), Aggregation.unwind("firstTable"), Aggregation.match(Criteria.where("firstTable.name").is("xxx")) AggregationResults<ThirdTable> results = mongoTemplate.aggregate(aggregation, "thirdTable", ThirdTable.class); return results.getMappedResults(); 以上代码中,"thirdTable"、"secondTable"、"firstTable" 分别对应三个集合的名称,"secondTableId"、"firstTableId" 分别对应第二个表和第三个表中与第一个表关联的字段,"name" 是第一个表中的一个字段,用于筛选符合条件的记录。最终返回的是符合条件的第三个表的记录列表。