将AggregationOutput转换为JsonObject

时间:2015-06-29 07:55:11

标签: java json mongodb aggregation-framework jsonobject

我有一个使用JAVA驱动程序运行mongodb查询的程序。我将结果存储到AggregationOutput中。我想将reult转换为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并将其返回给其他函数。如何做?

1 个答案:

答案 0 :(得分:2)

使用Java JSON jargson jar,我使用Java JSON Jar。如下所示更改循环:

    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);