Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 598
nuvio Avatar asked Jul 17 '26 17:07

nuvio


1 Answers

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);
}
like image 77
tenorsax Avatar answered Jul 20 '26 06:07

tenorsax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!