我想了解如何使用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
会返回该集合所包含文档的总数。
答案 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));