Java+mongodbTemplate聚合查询
第一次使用mongodbTemplate进行聚合查询踩得一些坑,废话不多说直接上代码:`
@ApiModel(value = "JdgParameterRuleDto", description = "测试类")
public class JdgParameterRuleDto implements Serializable {
private static final long serialVersionUID = -7421289160530155401L;
/**
* 主键
*/
@ApiModelProperty(name = "_id", value = "主键")
private ObjectId _id;
/**
* 附表对应id
*/
@ApiModelProperty(name = "test_id", value = "附表对应id")
private String test_id;
/**
* 附表对应code
*/
@ApiModelProperty(name = "par_channel_code", value = "附表对应code")
private String test_code;
/**
* 判读级别(1:一级2:二级3:三级)
*/
@ApiModelProperty(name = "sts_level", value = "判读级别(1:一级2:二级3:三级)")
private Integer sts_level;
private List<BasicParameter> basic_parameter;
}
注意事项:1.在java中对应的实体类字段一定要和mongodb中对应的表字段一模一样,否则返回值对象会因为字段名称不一场而查不到值 2.在上述实体类中除了basic_parameter这个List对象其余字段全部为主表字段,附表数据应该用List对象进行接收,否则查询不到相应数据 以下代码为mongodbTemplate的聚合查询代码:
/**
* 多表联合查询,
* @param <T>
* @return
*/
@Override
public <T> List<T> relationQueryMoreToOne(Map<String, Object> paramMap, Class<T> entityClass) {
LookupOperation lookup = LookupOperation.newLookup()
//从表(关联的表)
.from("basic_parameter")
//主表中与从表相关联的字段
.localField("test_id")
//从表与主表相关联的字段
.foreignField("test_id")
//查询出的从表集合 命名(相当于从表的别名
.as("basic_parameter");
Aggregation aggregation = null;
//主表查询条件可以给可以不给i
AggregationOperation match = null;
if(paramMap.get("par_channel_code") != null){
Criteria ordercri = Criteria.where("par_channel_code").is(paramMap.get("par_channel_code").toString());
match = Aggregation.match(ordercri);
aggregation = Aggregation.newAggregation(match,lookup);
}
//次表查询条件可以给可以不给
AggregationOperation match1 = null;
if(paramMap.get("subsys_code") != null){
Criteria ordercri1 = Criteria.where("subsys_code").is(paramMap.get("subsys_code").toString());
match1 = Aggregation.match(ordercri1);
}
//查询条件
if (match != null && match1 != null){
aggregation = Aggregation.newAggregation(match,lookup,match1);
}else if(match == null && match1 == null){
aggregation = Aggregation.newAggregation(lookup);
}else if(match != null && match1 == null){
aggregation = Aggregation.newAggregation(match,lookup);
}else if(match == null && match1 != null){
aggregation = Aggregation.newAggregation(lookup,match1);
}
// List<AggregationOperation> operations = new ArrayList<>();
// operations.add(lookup);
// aggregation = Aggregation.newAggregation(operations);
// entityClass这个参数为返回值对象即上边的JdgParameterRuleDto
AggregationResults<T> studentAggregation = mongoTemplate.aggregate(aggregation, "jdg_parameter_rule", entityClass);
return (List<T>) studentAggregation.getMappedResults();
}
以为就是mongodbTemplate的聚合查询,第一次写帖子,不喜勿喷。
|