MongoTemplate高级查询,过滤—>排序—>分组—>去重(按照时间倒序取最新一条数据)
在使用MongoDB时遇到的复杂查询,需要对表数据进行分组,然后取出最新一条数据先看代码://object是泛型,是定义的数据库映射类private List<Object> getArchiveDataList(Request request) {TypedAggregation<Object> tagg = TypedAggregation.newAggregation
·
在使用MongoDB时遇到的复杂查询,需要对表数据进行分组,然后取出最新一条数据
先看代码:
//object是泛型,是定义的数据库映射类
private List<Object> getArchiveDataList(Request request) {
TypedAggregation<Object> tagg = TypedAggregation.newAggregation(Object.class,
Arrays.asList(
//筛选条件 过滤条件 这里举例了通过'createTime'进行范围查询
//后面atTime的作用是MongoDB的时区不一样,时区+8小时处理
TypedAggregation.match(Criteria.where("createTime")
.gte(request.getStartDate().atTime(8, 0, 0))
.lt(request.getEndDate().atTime(8, 0, 0).plusDays(1))),
//分组过滤条件,sort的顺序有要求,在分组方法前就是先排序后分组,反之道理一样
TypedAggregation.sort(Sort.by(Sort.Order.desc("createTime"))),
//排序字段 通过userId进行分组,意义:取某个人的最新一条数据,first,as里最后包含展示的字段
//first和as的作用是 first为MongoDB查询出的列值,as为将值放到类成员变量中,如果不使用任何的first和as,那么返回的映射类信息所有成员变量都是null
TypedAggregation.group("userId")
.first("userId").as("userId")
.first("name").as("name")
.first(request.getFiled()).as(request.getFiled())
//挑选需要字段
// TypedAggregation.project("activeCode", "startDate"),
)
);
AggregationResults<Object> result = mongoTemplate.aggregate(tagg, Object.class);
return result.getMappedResults();
}
具体的详解代码中都有注释,不懂的可以评论区进行讨论
更多推荐
已为社区贡献2条内容
所有评论(0)