2017-01-10 89 views
1

我想了解如何使用Mongo DB Java 3.x Driver實現group by查詢。我想通過usernames對我的收藏進行分組,並通過結果DESCcount對結果進行排序。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返回總數收集的文件。

回答

1

您應該儘量不要在Mongo 3.x中使用舊對象(BasicDBObject)類型。你可以嘗試這樣的事情。

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));