MongoDB使用Template查询数据
MongoDB,Template,分组查询,Aggregation
·
1.用实体类查询
@Document("AnalysisIndex")
@Data
public class AnalysisIndex implements Serializable {
/**
* id
*/
@Field("_id")
@ApiModelProperty(name = "id", value = "主键", hidden = false)
private String id;
/**
* 公司id
*/
@Field("company_id")
@ApiModelProperty(name = "companyId", value = "公司id", hidden = false)
private String companyId;
/**
* 时间
*/
@Field("event_date")
@ApiModelProperty(name = "eventDate", value = "时间", hidden = false)
private String eventDate;
/**
* 全站流量
*/
@Field("visit_pv")
@ApiModelProperty(name = "visitPv", value = "全站流量", hidden = false)
private String visitPv;
/**
* 全站流量
*/
@Field("visit_nv")
@ApiModelProperty(name = "visitNv", value = "全站流量", hidden = false)
private String visitNv;
/**
* 总新增用户
*/
@Field("visit_uv")
@ApiModelProperty(name = "visitUv", value = "总新增用户", hidden = false)
private String visitUv;
/**
* 注册用户数
*/
@Field("visit_rv")
@ApiModelProperty(name = "visitRv", value = "注册用户数", hidden = false)
private String visitRv;
/**
* 平均访问时长
*/
@Field("visit_duration")
@ApiModelProperty(name = "visitDuration", value = "平均访问时长", hidden = false)
private String visitDuration;
}
Criteria criteria = Criteria.where("event_date").gte(dateMap.get("from_date"))
.lte(dateMap.get("to_date")).and("company_id").is(param.getCompanyId()).and("project").is(project);
Query query=new Query();
query.addCriteria(criteria);
// 按创建时间倒序
query.with(Sort.by(
Sort.Order.desc("event_date")
));
//查询的表在实体类里面
List<AnalysisIndex> analysisIndices = mongoTemplate.find(query, AnalysisIndex.class);
2.分组查询
Criteria criteria = Criteria.where("event_date").gte(dateMap.get("from_date"))
.lte(dateMap.get("to_date")).and("company_id").is(param.getCompanyId()).and("project").is(project);
//查询的表在实体类里面
//根据target_type分组,first就是取第一个字段,as就是返回的字段名称,count就是去分组的总数放入value里面 相当与 select target_type as key,count(target_type)as value group by target_type
Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
Aggregation.group("company_id")
.first("company_id").as("company_id")
.sum("visit_pv").as("visit_pv")
.sum("visit_rv").as("visit_rv")
.sum("visit_nv").as("visit_nv")
.sum("event_date").as("event_date")
.sum("visit_uv").as("visit_uv")
.sum("visit_duration").as("visit_duration")
//二个字段相乘 相加ArithmeticOperators.Add 相除ArithmeticOperators.Divide 相减ArithmeticOperators.Subtract
.sum(ArithmeticOperators.Multiply.valueOf("visit_duration").multiplyBy("visit_uv")).as("duration"),
Aggregation.sort(Sort.Direction.DESC, "event_date"));
AggregationResults<AnalysisIndex> results = mongoTemplate.aggregate(aggregation, "AnalysisIndex",
AnalysisIndex.class);
List<AnalysisIndex> analysisIndices = results.getMappedResults();
更多推荐
已为社区贡献2条内容
所有评论(0)