正在将AggregationOutput转换为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,并将其返回给其他函数。怎么做?

使用Java JSON jar或gson 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);

相关内容

  • 没有找到相关文章

最新更新