MongoDB mongoTemplate查询条作组合例子

[b]MongoDB mongoTemplate查询条作组合例子[/b]


[b]常规查询[/b]
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<DeviceOnlineStatisticsModel> deviceOnlineStatisticsModelList = mongoTemplate.find(query,
DeviceOnlineStatisticsModel.class);

if (deviceOnlineStatisticsModelList.size() == 0) {
return null;
}
return deviceOnlineStatisticsModelList.get(0);
}



public List<DeviceOnlineReport> 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//查询语句


[b]聚合查询[/b]
public DeviceOnlineReport findtest() {
TypedAggregation<DeviceOnlineReport> 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<BasicDBObject> 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<String> collection = new ArrayList<>();
collection.add("0");
collection.add("1");

TypedAggregation<DeviceOnlineReport> 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<BasicDBObject> 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<OnlineTime> 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<DeviceOnlineTimeStatisticsModel> aggregation = Aggregation.newAggregation(
DeviceOnlineTimeStatisticsModel.class, matchOperation, projectionOperationYear, groupOperation,
projectionOperation);

logger.info(logString + " agg == " + aggregation.toString());
// 执行聚合函数
AggregationResults<OnlineTime> result = mongoTemplate.aggregate(aggregation, OnlineTime.class);
// logger.info(logString + " result == " + result.getMappedResults());

List<OnlineTime> onlineNunList = result.getMappedResults();

logger.info(logString + " onlineNunList == " + onlineNunList.toString());
return onlineNunList;
}



(MongoDB的聚合查询(两种方式)):[url]http://www.cnblogs.com/ontheroad_lee/p/3756247.html[/url]
(MongoDB 聚合管道(Aggregation Pipeline)):[url]http://www.cnblogs.com/shanyou/p/3494854.html[/url]
(MongoDB的聚合查询(两种方式)):[url]http://blog.csdn.net/luckycz/article/details/46924995[/url]
(Aggregation Grouping Example):[url]http://www.mkyong.com/mongodb/spring-data-mongodb-aggregation-grouping-example/[/url]
(Spring data mongodb聚合查询):[url]http://wenku.baidu.com/link?url=fdgkdGYnqsBRQfR6g1y78ZPJ77huzJ9ZOzIZeQU1cGkCZNTblirRZhjE0EEToHQEjTDSPJahgpC10ZHzr4iPFiqyuBT9oNLYLg8PQ4SZeGa[/url]
(Spring Data MongoDB,英文):[url]http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.aggregation[/url]
(Spring Data MongoDB(Query and Projection Operators),英文):[url]https://docs.mongodb.com/v3.2/reference/operator/query/[/url]
(Aggregation Pipeline基础篇上):[url]http://blog.csdn.net/congcong68/article/details/51619882[/url]
(MongoDB分组汇总操作):[url]http://www.cnblogs.com/zhuxiaojie/p/6007267.html[/url]
(MongoDB按时间分组):[url]http://stackoverflow.com/questions/26770324/how-to-build-combined-id-property-of-the-group-in-mongo-aggregation-using-spri[/url]
(MongoDB按页查询):[url]http://blog.csdn.net/itmyhome1990/article/details/52240900[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值