概述
MongoDB mongoTemplate查询条作组合例子
常规查询
public DeviceOnlineStatisticsModel findByKeyAndTimeDateMax(String key) {
Sort sort = new Sort(new Order(Direction.DESC, "timeDate"));
Criteria criteria = Criteria.where("key").is(key); //
Query query = new Query(criteria);
query.with(sort).limit(1);
List deviceOnlineStatisticsModelList = mongoTemplate.find(query,
DeviceOnlineStatisticsModel.class);
if (deviceOnlineStatisticsModelList.size() == 0) {
return null;
}
return deviceOnlineStatisticsModelList.get(0);
}
public List findBetweenTimeDate(Date timeDateStart, Date timeDateEnd) {
Criteria criteria = Criteria.where("timeDate").gte(timeDateStart).lt(timeDateEnd);
Query query = new Query(criteria);
return mongoTemplate.find(query, DeviceOnlineReport.class);
}
Criteria//是条件
Sort//排序
Query//查询语句
聚合查询
public DeviceOnlineReport findtest() {
TypedAggregation agg = Aggregation.newAggregation(DeviceOnlineReport.class,
Aggregation.group("onlineStatus").count().as("num"),
Aggregation.project("num").and("onlineStatus").previousOperation()// 结果包含那些字段(num),挑选所需的字段,用"onlineStatus"显示分组的类型,并且不输出以“_id”分组的结果
);
System.out.println(" agg == " + agg.toString());
// { "aggregate" : "__collection__" , "pipeline" : [ { "$group" : {"_id" : "$onlineStatus" , "num" : { "$sum" : 1}}} , { "$project" : {"num" : 1 , "_id" : 0 , "onlineStatus" : "$_id"}}]}
AggregationResults result = mongoTemplate.aggregate(agg, BasicDBObject.class);
// [{ "num" : 3 , "onlineStatus" : "1"}, { "num" : 3 , "onlineStatus" :"0"}]
result.getMappedResults();
System.out.println(" result.getMappedResults == " + result.getMappedResults().toString());
List list = new ArrayList<>();
DeviceOnlineReport deviceOnlineReport = new DeviceOnlineReport();
return deviceOnlineReport;
}
public DeviceOnlineReport findtest3() {
List collection = new ArrayList<>();
collection.add("0");
collection.add("1");
TypedAggregation agg = Aggregation.newAggregation(DeviceOnlineReport.class,
Aggregation.match(Criteria.where("onlineStatus").in(collection)), //条件匹配 (timeDate)minute(timeDate)
Aggregation.project("timeDate").andExpression("hour(timeDate)").as("hour"), //andExpression对某个字段执行Mongo命令,并作为新的字段(testTime)
Aggregation.group("hour").count().as("num"),
Aggregation.project("num").and("hour").previousOperation()// 结果包含那些字段(num),挑选所需的字段,用"onlineStatus"显示分组的类型,并且不输出以“_id”分组的结果
);
System.out.println(" agg == " + agg.toString());
//{ "aggregate" : "__collection__" , "pipeline" : [ { "$match" : { "onlineStatus" : { "$in" : [ "0" , "1"]}}} , { "$project" : { "timeDate" : 1 , "hour" : { "$hour" : [ "$timeDate"]}}} , { "$group" : { "_id" : "$hour" , "num" : { "$sum" : 1}}} , { "$project" : { "num" : 1 , "_id" : 0 , "hour" : "$_id"}}]}
AggregationResults result = mongoTemplate.aggregate(agg, BasicDBObject.class);//BasicDBObject
result.getMappedResults();
System.out.println(" result.getMappedResults == " + result.getMappedResults().toString());
//[{ "num" : 6 , "hour" : 5}]
List list = new ArrayList<>();
DeviceOnlineReport deviceOnlineReport = new DeviceOnlineReport();
return deviceOnlineReport;
}
public List deviceOnlineTimeStatisticsFromData(
DeviceOnlineTimeStatisticsParamModel deviceOnlineTimeStatisticsParamModel) {
String logString = "DeviceOnlineTimeStatisticsService deviceOnlineTimeStatisticsService: ";
logger.info(logString + "deviceOnlineTimeStatisticsParamModel == "
+ deviceOnlineTimeStatisticsParamModel.toString());
// 构造符合条件的Criteria
String deviceId = deviceOnlineTimeStatisticsParamModel.getDeviceId();
String deviceType = deviceOnlineTimeStatisticsParamModel.getDeviceType();
String modelNo = deviceOnlineTimeStatisticsParamModel.getModelNo();
String cityId = deviceOnlineTimeStatisticsParamModel.getCityId();
Date startDate = deviceOnlineTimeStatisticsParamModel.getStartDate();
Date endDate = deviceOnlineTimeStatisticsParamModel.getEndDate();
if (startDate == null) {
startDate = new Date(0, 0, 1);
}
if (endDate == null) {
endDate = new Date();
}
logger.info(logString + " startDate == " + startDate);
logger.info(logString + " endDate == " + endDate);
// 结束时间小于起始时间
if (endDate.before(startDate)) {
logger.info(logString + " endDate < startDate");
return null;
}
Criteria criteria = null;
if (StringUtils.isNotBlank(deviceType)) {
criteria = Criteria.where("deviceType").is(deviceType);
} else {
criteria = Criteria.where("deviceType").ne(null);
}
if (StringUtils.isNotBlank(deviceId)) {
criteria.and("deviceId").is(deviceId);
}
if (StringUtils.isNotBlank(modelNo)) {
criteria.and("modelNo").is(modelNo);
}
if (StringUtils.isNotBlank(cityId)) {
criteria.and("cityId").is(cityId);
}
criteria.and("offlineDate").gte(startDate).lt(endDate);
//
// 确定分组方式
String groupBy = null;
if (deviceOnlineTimeStatisticsParamModel.getGroupType() == 1) {
groupBy = "deviceType";// deviceType
} else if (deviceOnlineTimeStatisticsParamModel.getGroupType() == 2) {
groupBy = "modelNo";// modelNo
} else if (deviceOnlineTimeStatisticsParamModel.getGroupType() == 3) {
groupBy = "cityId";// cityId
} else if (deviceOnlineTimeStatisticsParamModel.getGroupType() == 4) {
groupBy = "deviceId";// deviceId
} else {
groupBy = "deviceType";// deviceType
}
// match
MatchOperation matchOperation = Aggregation.match(criteria);// 条件匹配
// ProjectionOperation projectionOperationYear = Aggregation
// .project("deviceType", "offlineDate", "deviceId", "timeLen",
// "onlineDate", "src", "modelNo")
// .andExpression("year(offlineDate)").as("year").andExpression("month(offlineDate)").as("month");
// ProjectionOperation projectionOperationYear = Aggregation
// .project("deviceType", "offlineDate", "deviceId", "timeLen",
// "onlineDate", "src", "modelNo")
// .andExpression("year(offlineDate)").as("year").andExpression("month(offlineDate)").as("month").and(groupBy).as("groupKey");
//要写成一行,它是以管道的方式进行的,也可以写成多个,但字段是一层层流过去的,你这一层没有,后面的都会没有的
ProjectionOperation projectionOperationYear = Aggregation
.project("deviceType", "offlineDate", "deviceId", "timeLen", "onlineDate", "src", "modelNo")
.andExpression("year(offlineDate)").as("year").andExpression("month(offlineDate)").as("month");
logger.info(logString + " projectionOperationYear == " + projectionOperationYear.toString());
// group
GroupOperation groupOperation = Aggregation.group(groupBy, "year", "month").sum("timeLen").as("timeLen");
logger.info(logString + " groupOperation == " + groupOperation.toString());
// project//
// 结果包含那些字段(num),挑选所需的字段,用"onlineStatus"显示分组的类型,并且不输出以“_id”分组的结果
// ProjectionOperation projectionOperation =
// Aggregation.project("timeLen", "year", "month").and("groupKey")
// .previousOperation();
//结果:
//{
//"groupKey":"{ "deviceType" : "0xEF" , "year" : 2016 , "month" : 12}",
//"timeLen":70988000
//}
ProjectionOperation projectionOperation = Aggregation.project(groupBy, "timeLen", "year", "month").and(groupBy)
.as("groupKey").andExclude("_id");
//结果:
//{
// "groupKey":"00000025",
// "month":12,
// "timeLen":440078000,
// "year":2016
//}
logger.info(logString + " projectionOperation == " + projectionOperation.toString());
// 构造聚合函数
TypedAggregation aggregation = Aggregation.newAggregation(
DeviceOnlineTimeStatisticsModel.class, matchOperation, projectionOperationYear, groupOperation,
projectionOperation);
logger.info(logString + " agg == " + aggregation.toString());
// 执行聚合函数
AggregationResults result = mongoTemplate.aggregate(aggregation, OnlineTime.class);
// logger.info(logString + " result == " + result.getMappedResults());
List onlineNunList = result.getMappedResults();
logger.info(logString + " onlineNunList == " + onlineNunList.toString());
return onlineNunList;
}
(MongoDB的聚合查询(两种方式)):http://www.cnblogs.com/ontheroad_lee/p/3756247.html
(MongoDB 聚合管道(Aggregation Pipeline)):http://www.cnblogs.com/shanyou/p/3494854.html
(MongoDB的聚合查询(两种方式)):http://blog.csdn.net/luckycz/article/details/46924995
(Aggregation Grouping Example):http://www.mkyong.com/mongodb/spring-data-mongodb-aggregation-grouping-example/
(Spring data mongodb聚合查询):http://wenku.baidu.com/link?url=fdgkdGYnqsBRQfR6g1y78ZPJ77huzJ9ZOzIZeQU1cGkCZNTblirRZhjE0EEToHQEjTDSPJahgpC10ZHzr4iPFiqyuBT9oNLYLg8PQ4SZeGa
(Spring Data MongoDB,英文):http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.aggregation
(Spring Data MongoDB(Query and Projection Operators),英文):https://docs.mongodb.com/v3.2/reference/operator/query/
(Aggregation Pipeline基础篇上):http://blog.csdn.net/congcong68/article/details/51619882
(MongoDB分组汇总操作):http://www.cnblogs.com/zhuxiaojie/p/6007267.html
(MongoDB按时间分组):http://stackoverflow.com/questions/26770324/how-to-build-combined-id-property-of-the-group-in-mongo-aggregation-using-spri
(MongoDB按页查询):http://blog.csdn.net/itmyhome1990/article/details/52240900
分享到:
2016-12-01 17:08
浏览 23642
分类:互联网
评论
最后
以上就是顺心发卡为你收集整理的mongotemplate 查list_MongoDB mongoTemplate查询条作组合例子的全部内容,希望文章能够帮你解决mongotemplate 查list_MongoDB mongoTemplate查询条作组合例子所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复