我在MongoDB中有一个包含50,000条记录的集合。当我尝试在网页上显示它时,这会花费很多时间(大约15,000条记录需要7分钟)
我已经尝试使用Indexing,但是它不起作用。我在控制器中编写了一种方法来从XYZ集合中获取数据(我一次循环读取500条记录)。前端方法并使用其数据显示。
这是我的Controller方法: Maincontroller.java:
public List<Data> getDataBetweenDates(String startDate, String endDate) {
List<Data> DataList = null;
Calendar cal = Calendar.getInstance();
// change regex accordingly
String[] start = startDate.split("-");
String[] end = endDate.split("-");
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(start[0]));
cal.set(Calendar.MONTH, Integer.parseInt(start[1]) - 1);
cal.set(Calendar.YEAR, Integer.parseInt(start[2]));
String startDateInMillis = cal.getTimeInMillis() + "";
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(end[0]));
cal.set(Calendar.MONTH, Integer.parseInt(end[1]) - 1);
cal.set(Calendar.YEAR, Integer.parseInt(end[2]));
String endDateInMillis = cal.getTimeInMillis() + "";
System.out.println("start = " + startDateInMillis + " end = " + endDateInMillis);
try {
DataList = DataDao.getDataBetweenDates(startDateInMillis, endDateInMillis);
} catch (Exception e) {
e.printStackTrace();
}
return DataList;
}
这是Dao方法的实现:
@Override
public List<Data> getDataBetweenDates(String startDate, String endDate) throws Exception {
List<Data> DataList = new ArrayList<>();
JSONObject jObj = null;
JSONObject query = new JSONObject();
JSONObject start = new JSONObject();
start.put("$gte",startDate);
start.put("$lte", endDate);
query.put("timestamp", start);
long totalCount = dbService.count(Data.COLLECTION, query);
for(int j = 0 ; j <= totalCount; j+=500){
jObj = dbService.find(Data.COLLECTION, query, new JSONObject(),new JSONObject(),j,500);
if (!jObj.has("value")) {
return DataList;
}
for (int i = 0; i < jObj.getJSONArray("value").length(); i++) {
Data Data = gson.fromJson(jObj.getJSONArray("value").getJSONObject(i).toString(), Data.class);
DataList.add(Data);
}
}
jObj = null;
query = null;
return DataList;
}
有什么方法可以减少加载时间。