Mongo 数据库 Java 3.x 驱动程序 - 按查询分组
Mongo DB Java 3.x Driver - Group By Query
我想了解如何使用 Mongo DB Java 3.x Driver
实现 group by
查询。我想通过 usernames
将我的 collection 分组,并按结果 DESC
.
的 count
对结果进行排序
这是我要实现 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
returns collection 拥有的 文档总数 。
您应该尽量不要将旧对象 (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));
我想了解如何使用 Mongo DB Java 3.x Driver
实现 group by
查询。我想通过 usernames
将我的 collection 分组,并按结果 DESC
.
count
对结果进行排序
这是我要实现 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
returns collection 拥有的 文档总数 。
您应该尽量不要将旧对象 (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));