接上篇沛励,插入測試成功后特漩,接下來進(jìn)行查詢
檢索條件主要使用DBObject接口革半,BasicDBObject實(shí)現(xiàn)類
/**
* 查詢測試
*/
@Test
public void selectTest() {
Calendar calendar = Calendar.getInstance();
/* 之前一小時(shí)的數(shù)據(jù) */
//========== 1 進(jìn)行插入
HotAnls hot = new HotAnls();
hot.setCategory(1);
hot.setDateRange(7);
hot.setHotFeelIndex(90L);
hot.setWorkTime(new Date());
mongoTemplate.save(hot);
//========== 2 進(jìn)行檢索
// 創(chuàng)建DBObject 存儲操作用條件用的
DBObject cond = new BasicDBObject();
// 添加條件category = 1
cond.put("category", 1);
// 添加條件 >= 一小時(shí)前
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
cond.put("workTime", new BasicDBObject(QueryOperators.GTE, calendar.getTime()));
// 添加OR條件,與上面是AND關(guān)系慎皱,下面兩個(gè)hotFeelIndex是OR關(guān)系
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);
// 創(chuàng)建OR關(guān)系
cond.put(QueryOperators.OR, orList);
//限制查詢返回的字段 0或者1 只能同時(shí)存在一種
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"));
// 限制條數(shù)
query.skip(0).limit(50);
// 查詢 返回list
List<HashMap> result = mongoTemplate.find(query, HashMap.class, "hotAnls");
System.out.println(result.toString());
}