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
返回總數收集的文件。