mongoTemplate查询数据方式

方式一:

Query query = new Query();
// 时间区间
if (StrUtil.isNotEmpty(param.getExpenseTimeBegin()) && StrUtil.isNotEmpty(param.getExpenseTimeEnd())) {
	query.addCriteria(Criteria.where("statisticsDatetime").gte(param.getExpenseTimeBegin()).lte(param.getExpenseTimeEnd()));
}
// 门店
if (param.getStoreId() != null) {
	query.addCriteria(Criteria.where("storeId").is(param.getStoreId()));
}
// 父门店
if (param.getParentStoreId() != null) {
	query.addCriteria(Criteria.where("parentStoreId").is(param.getParentStoreId()));
}

List statisticsList = mongoTemplate.find(query, ContractItemExpenseStatistics.class, MongodbTableEnum.expense_statistics.getValue());

此方式在数据量较大的情况下速度会比较慢,需要将数据全部取出来,然后再映射成实体类,在数据量比较大的话不推荐这种方式

方式二:

DBObject  query = new BasicDBObject(); //setup the query criteria 设置查询条件
// 时间区间
if (StrUtil.isNotEmpty(param.getExpenseTimeBegin()) && StrUtil.isNotEmpty(param.getExpenseTimeEnd())) {
	query.put("statisticsDatetime", new BasicDBObject("$gte", param.getExpenseTimeBegin()).append("$lte", param.getExpenseTimeEnd()));
}
// 门店
if (param.getStoreId() != null) {
	query.put("storeId", param.getStoreId());
}
// 父门店
if (param.getParentStoreId() != null) {
	query.put("parentStoreId", param.getParentStoreId());
}

DBObject fields = new BasicDBObject(); //only get the needed fields. 设置需要获取哪些域
fields.put("statisticsDatetime", 1);
fields.put("storeId", 1);
fields.put("parentStoreId", 1);
fields.put("expenseStatisticsList", 1);

DBCursor dbObjects = mongoTemplate.getCollection(MongodbTableEnum.expense_statistics.getValue()).find(query, fields);

log.debug("开始时间:" + DateUtil.formatDateTime(new Date()));
int j = 0;

List statisticsList = new ArrayList<>();
while (dbObjects.hasNext()) {
	DBObject next = dbObjects.next();
	j = j + 1;
	ContractItemExpenseStatistics statistics = new ContractItemExpenseStatistics();

	// 各个项目统计数据
	try {
		JSONArray jsonArray = JSONUtil.parseArray(next.get("expenseStatisticsList"));
		List expenseStatisticsList = new ArrayList<>();
		for (int i = 0; i < jsonArray.size(); i++) {
			ExpenseStatisticsJsonVo jsonVo = JSONUtil.toBean(jsonArray.get(i).toString(), ExpenseStatisticsJsonVo.class);
			expenseStatisticsList.add(jsonVo);
		}
		statistics.setExpenseStatisticsList(expenseStatisticsList);
		statistics.setStatisticsDatetime(next.get("statisticsDatetime").toString());
		statistics.setStoreId(Integer.parseInt(next.get("storeId").toString()));
		statistics.setParentStoreId(Integer.parseInt(next.get("parentStoreId").toString()));
		statisticsList.add(statistics);
	}catch (Exception e){
		e.printStackTrace();
	}
}
log.debug("结束时间:" + DateUtil.formatDateTime(new Date()));
log.debug("j=" + j);

这种方法是使用的游标的方式,使用游标逐个获取数据,同时可以指定只获取哪些域,而不是全部获取回来,所以数据量比较大的时候还是使用游标的方式手动映射成实体类比较快!

你可能感兴趣的:(mongodb)