1
我想了解如何使用Mongo DB Java 3.x Driver
实现group by
查询。我想通过usernames
对我的收藏进行分组,并通过结果DESC
的count
对结果进行排序。Mongo DB Java 3.x驱动程序 - 按查询分组
这里是壳查询,我要实现的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
分组。 countOfResults
返回总数收集的文件。