Search code examples
javamongodbpojoaggregation-framework

parsing AggregationOutput mongo java driver


I have an aggregate that returns 3 results

{ "serverUsed" : "/127.0.0.1:27017" , "result" : [ { "_id" : "luke" , "times" : 56} , { "_id" : "albert" , "times" : 28} , { "_id" : "matt" , "times" : 28}] , "ok" : 1.0}

however when I try to iterate over the results, the code enter an endless loop (can't understand why!!)

AggregationOutput output = coll.aggregate( match1, unwind, match2, group, sort, limit);

Iterable<DBObject> list= output.results();
        while(list.iterator().hasNext()){

            String id = (String) list.iterator().next().get("_id");
            int times = Integer.parseInt(list.iterator().next().get("times").toString());

            System.out.println("ID IS "+id+" time: "+times);
        }

Also the output repeats the first result:

ID IS luke time: 56
ID IS luke time: 56
ID IS luke time: 56
ID IS luke time: 56
ID IS luke time: 56
...

I really don;t understand why this iteration is not working. Please help!


Solution

  • It seems that you are using new iterator every time you access a field in DBObject, ie you're using list.iterator() several times within the loop. list.iterator().next() returns you the first element in the collection. So you end up accessing the first DBObject.

    Try this:

    Iterable<DBObject> list= output.results();
    while(list.iterator().hasNext()){
        DBObject obj = list.iterator().next();
        String id = obj.get("_id");
        int times = Integer.parseInt(obj.get("times").toString());
    
        System.out.println("ID IS "+id+" time: "+times);
    }
    

    Or perhaps use a foreach loop:

    for (DBObject obj : output.results()) {
        String id = obj.get("_id");
        int times = Integer.parseInt(obj.get("times").toString());
        System.out.println("ID IS "+id+" time: "+times);
    }