如何使用mongodb和Java获得列表格式的输出?

如何使用mongodb和Java获得列表格式的输出?,java,mongodb,Java,Mongodb,我使用java和mongoDB来获取特定键的值之和 以下是我的工作: ArrayList<BasicDBObject> pipeline = new ArrayList<BasicDBObject>(); JSONArray networkCapacityTrending = new JSONArray(); BasicDBObject cmdBody = new BasicDBObject("aggregate",networkRealtime.toString());

我使用java和mongoDB来获取特定键的值之和

以下是我的工作:

ArrayList<BasicDBObject> pipeline = new ArrayList<BasicDBObject>();
JSONArray networkCapacityTrending = new JSONArray();
BasicDBObject cmdBody = new BasicDBObject("aggregate",networkRealtime.toString());
BasicDBObject match = new BasicDBObject();
//set query to DB 

pipeline.add(new BasicDBObject("$match", match));
pipeline.add(new BasicDBObject(new BasicDBObject("$group",
new BasicDBObject("_id", "$runtimeMillis").append("total",
new BasicDBObject("$sum", "$totInOutOctets")))));
pipeline.add(new BasicDBObject("$sort", new BasicDBObject("_id", 1)));
cmdBody.put("pipeline", pipeline);

// Put db command for execution in json array
networkCapacityTrending.put(db.command(cmdBody));
JSONObject obj;
JSONArray result = new JSONArray();
try {
    obj = networkCapacityTrending.getJSONObject(0);
    result = obj.getJSONArray("result");
} catch (JSONException e) {
    Logger.error("Error while getting network capacity trending "
    + e.getMessage());
}
但我希望输出为 [1403259896382,30],[1403259854796,10],[1403259854996,50]…]


如何查询文档以获得所需的输出?

您只需迭代JSONArray并形成如下列表:

   ArrayList<ArrayList<Long>> final_arr = new ArrayList<ArrayList<Long>>();
        for (int i = 0; i < result.length(); i++) {
            ArrayList<Long> array_int = new ArrayList<Long>();
            int aInt = result.getJSONObject(i).getInt("total");
            array_int.add(result.getJSONObject(i).getLong("_id"));
            array_int.add(new Long(aInt));
            final_arr.add(array_int);
        }
   System.out.println(final_arr);
在上面的代码中,结果是JSONArray,其值为:[{u-id:1403259854796,total:0},{u-id:1403259896382,total:0},{u-id:1403265301824,total:0}]


最后的_arr包含所需的输出:[[1403259854796,0],[1403259896382,0],[1403265301824,0]

通过迭代列表的子项来处理结果,并创建一个包含ID和附加的总值的字符串。问题到底出在哪里?但我希望输出为[[1403259896382,30],[1403259854796,10],[1403259854996,50]…]@user3322141输出的格式是您想要的,运行并检查。@user3322141您是在谈论输出的格式还是值??关于输出的格式。我想用这个输出在网页上画一个图表。我不想要数据中的键和总数
   ArrayList<ArrayList<Long>> final_arr = new ArrayList<ArrayList<Long>>();
        for (int i = 0; i < result.length(); i++) {
            ArrayList<Long> array_int = new ArrayList<Long>();
            int aInt = result.getJSONObject(i).getInt("total");
            array_int.add(result.getJSONObject(i).getLong("_id"));
            array_int.add(new Long(aInt));
            final_arr.add(array_int);
        }
   System.out.println(final_arr);