1

我想用 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}

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

4

1 回答 1

1

MongoDB javadoc 给出了答案:AggregationOutput有一个.results()返回Iterable结果的方法。

并且Iterable可以在 foreach 循环中使用“手段”。像这样:

for (final DBObject result: output.results())
    // do something with the result
于 2013-07-05T05:57:25.573 回答