我如何使用java将Mongodb中的列分组?

时间:2017-03-17 06:39:33

标签: java mongodb group-by

{"amount":100,"NAME":"dgsdg","ID":1}
{"amount":200,"NAME":"fdfd","ID":2}
{"amount":300,"NAME":"jfhjd","ID":3}
{"amount":400,"NAME":"kjhfjh","ID":4}
{"amount":500,"NAME":"kjjdj","ID":5}
{"amount":300,"NAME":"fdfd","ID":6}

我想按名称执行分组 我能够做到收集。

MongoDatabase database = client.getDatabase("db");
MongoCollection<Document> collection = database.getCollection("test");
 MongoCollection<Document> myColl =  (MongoCollection<Document>) collection.aggregate(Arrays.asList(Aggregates.group("$Name", Accumulators.sum("amount", 1))));
          FindIterable<org.bson.Document> it = myColl.find();

            MongoCursor<org.bson.Document> cursor = it.iterator();
            //System.out.println(cursor.next());
            Map s = cursor.next();
            JSONObject j = new JSONObject(s);

给我异常: java.lang.ClassCastException:com.mongodb.AggregateIterableImpl无法强制转换为com.mongodb.client.MongoCollection

0 个答案:

没有答案