1

我想学习如何group by使用Mongo DB Java 3.x Driver. 我想通过 对我的集合进行分组,并按结果对结果usernames进行排序。countDESC

这是我想实现Java等效的shell查询:

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返回集合拥有的文档总数

4

1 回答 1

1

您应该尽量不要在BasicDBObjectMongo 3.x 中使用旧的 object ( ) 类型。你可以尝试这样的事情。

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));
于 2017-01-10T20:45:10.077 回答