将 AggregationOutput 转换为 JsonObject

Converting AggregationOutput to JsonObject

我有一个使用 JAVA driver.I 运行 mongodb 查询的程序正在将结果存储到 AggregationOutput 中。我想将结果转换为 JsonObject 并将其传递给其他函数。

这是我的代码:

public class JavaAggregation {

public static JsonObject ja() throws UnknownHostException{
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("mydb");

DBCollection coll = db.getCollection("tq");

final List<DBObject> pipeline = new ArrayList<>();

Calendar calendar = Calendar.getInstance();

final BasicDBObject matchObj = new BasicDBObject();

String timePeriod = "today";

switch(timePeriod){
case "today" :

int day = calendar.get(Calendar.DAY_OF_YEAR);  
String dayS = Integer.toString(day);
matchObj.put("$match", new BasicDBObject(
        "dayofyear", dayS));
    pipeline.add(matchObj);
break; 


case "week" :
int dayW = calendar.get(Calendar.DAY_OF_YEAR); 
int dayLW = dayW - 7;
String daySW = Integer.toString(dayW);
String daySLW = Integer.toString(dayLW);
matchObj.put("$match", new BasicDBObject("dayofyear",
           new BasicDBObject("$gte", daySLW).append("$lte", daySW) ));
    pipeline.add(matchObj);
break; 

 case "month" :
int dayM = calendar.get(Calendar.DAY_OF_YEAR); 
int dayLM = dayM - 30;
String daySM = Integer.toString(dayM);
String daySLM = Integer.toString(dayLM);
matchObj.put("$match", new BasicDBObject("dayofyear",
           new BasicDBObject("$gt", daySLM).append("$lte", daySM) ));
    pipeline.add(matchObj);
    break; 

default :
System.out.println("Invalid Entry");
} 
DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$term")
.append("totalcount", new BasicDBObject("$sum", "$count")));
pipeline.add(group);


DBObject sort1 = null;
BasicDBObject sortByCount = null;
sortByCount = new BasicDBObject( "totalcount", -1 );
sort1 = new BasicDBObject( "$sort", sortByCount);
pipeline.add(sort1);

AggregationOutput output = coll.aggregate(pipeline);

for (DBObject res : output.results()) {
    System.out.println(res);
}
}
}

输出:

{ "_id" : "aero" , "totalcount" : 26}
{ "_id" : "aero storm tour" , "totalcount" : 3}

我想将输出转换为 JsonObject,然后 return 将其转换为其他 function.How 来完成?

使用Java JSON jar or gson jar,这里我使用Java JSON Jar。更改 for 循环如下:

    JSONArray jsonArray = new JSONArray();
    for (DBObject res : output.results()) {
        System.out.println(res);
        JSONObject jsonobj = new JSONObject();
        jsonobj.put("_id", res.get("_id"));
        jsonobj.put("totalcount", res.get("totalcount"));
        jsonArray.put(jsonobj);
    }
    System.out.println(jsonArray);