接上篇,插入测试成功后,接下来进行查询
检索条件主要使用DBObject接口,BasicDBObject实现类
/**
* 查询测试
*/
@Test
public void selectTest() {
Calendar calendar = Calendar.getInstance();
/* 之前一小时的数据 */
//========== 1 进行插入
HotAnls hot = new HotAnls();
hot.setCategory(1);
hot.setDateRange(7);
hot.setHotFeelIndex(90L);
hot.setWorkTime(new Date());
mongoTemplate.save(hot);
//========== 2 进行检索
// 创建DBObject 存储操作用条件用的
DBObject cond = new BasicDBObject();
// 添加条件category = 1
cond.put("category", 1);
// 添加条件 >= 一小时前
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
cond.put("workTime", new BasicDBObject(QueryOperators.GTE, calendar.getTime()));
// 添加OR条件,与上面是AND关系,下面两个hotFeelIndex是OR关系
BasicDBList orList = new BasicDBList();
DBObject orCond1 = new BasicDBObject();
orCond1.put("hotFeelIndex", 90);
DBObject orCond2 = new BasicDBObject();
orCond2.put("hotFeelIndex", 30);
orList.add(orCond1);
orList.add(orCond2);
// 创建OR关系
cond.put(QueryOperators.OR, orList);
//限制查询返回的字段 0或者1 只能同时存在一种
DBObject feild = new BasicDBObject();
feild.put("dateRange", 1);//查询
// feild.put("_id", 0);//不查询
Query query = new BasicQuery(cond, feild);
query.with(new Sort(Sort.Direction.DESC, "age"));
// 限制条数
query.skip(0).limit(50);
// 查询 返回list
List<HashMap> result = mongoTemplate.find(query, HashMap.class, "hotAnls");
System.out.println(result.toString());
}
网友评论