Mongo DB Java 3.x驱动程序 - 按查询分组

时间:2017-01-10 20:35:50

标签: mongodb mongodb-query mongo-java mongo-java-driver

我想了解如何使用group by实施Mongo DB Java 3.x Driver查询。我想通过usernames对我的收藏进行分组,然后按结果count的{​​{1}}对结果进行排序。

以下是我要实现DESC等效的shell查询:

Java

以下是我已实施的db.stream.aggregate({ $group: {_id: '$username', tweetCount: {$sum: 1} } }, { $sort: {tweetCount: -1} } ); 代码:

Java

我需要的结果是按BasicDBObject groupFields = new BasicDBObject("_id", "username"); // count the results and store into countOfResults groupFields.put("countOfResults", new BasicDBObject("$sum", 1)); BasicDBObject group = new BasicDBObject("$group", groupFields); // sort the results by countOfResults DESC BasicDBObject sortFields = new BasicDBObject("countOfResults", -1); BasicDBObject sort = new BasicDBObject("$sort", sortFields); List < BasicDBObject > pipeline = new ArrayList < BasicDBObject > (); pipeline.add(group); pipeline.add(sort); AggregateIterable < Document > output = collection.aggregate(pipeline); 分组的文件数。 username会返回该集合所包含文档的总数

1 个答案:

答案 0 :(得分:1)

您应该尽量不要将旧对象(BasicDBObject)类型与Mongo 3.x一起使用。你可以尝试这样的事情。

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static java.util.Arrays.asList;

Bson group = group("$username", sum("tweetCount", 1));
Bson sort = sort(new Document("tweetCount", -1));
AggregateIterable <Document> output = collection.aggregate(asList(group, sort));