首页 > 解决方案 > java - 如何在Java中从Mongo DB获取或检索大数据到前端?

问题描述

我在 MongoDB 中有一个包含 50,000 条记录的集合。当我尝试在网页中显示它时。这需要很长时间(15000 条记录大约需要 7 分钟)

我已经尝试过使用索引,但它不起作用。我在控制器中编写了一个方法来从 XYZ 集合中获取数据(我在循环中一次读取 500 条记录)。我在方法中调用该方法前端并使用其数据进行显示。

这是我的控制器方法: 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;
    }

有什么办法可以减少加载时间。

标签: javaspringmongodbjspcontroller

解决方案


推荐阅读