在java中迭代聚合输出

时间:2013-07-05 05:53:30

标签: java mongodb

我想在mongo中写这个查询 -

select account, count(*) from OBD_active group by account;

我在java中编写代码 -

 DBObject match = new BasicDBObject("$match", new BasicDBObject() );

        DBObject fields = new BasicDBObject("account", 1);
        fields.put("status", 1);
        fields.put("_id", 0);
        DBObject project = new BasicDBObject("$project", fields );

        DBObject groupFields = new BasicDBObject( "count", "$account");
        groupFields.put("total", new BasicDBObject( "$sum", "$status"));
        DBObject group = new BasicDBObject("$group", groupFields);

        db = Connect.getConnection();
        coll = collection(db, "OBD_active");

        AggregationOutput output = coll.aggregate( match, project, group );


        System.out.println("Output is"+output);

  and getting output-



Output is{ "serverUsed" : "localhost/127.0.0.1:27017" , "result" : [ { "_id" : "relnew" , "total" : 3.0} , { "_id" : "tata" , "total" : 2.0}] , "ok" : 1.0}

结果还可以,但我想迭代这个结果,如何实现呢?

1 个答案:

答案 0 :(得分:1)

MongoDB javadoc给出答案:AggregationOutput has a .results() method which returns an Iterable over the results

并且Iterable“表示”可以在foreach循环中使用。就这样:

for (final DBObject result: output.results())
    // do something with the result