Mongo DB Java 3.x驱动程序-按查询分组 [英] Mongo DB Java 3.x Driver - Group By Query

查看:76
本文介绍了Mongo DB Java 3.x驱动程序-按查询分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习如何使用Mongo DB Java 3.x Driver实施group by查询.我想通过usernames对我的收藏进行分组,然后按结果DESCcount排序结果.

I'd like to learn how to implement group by query using Mongo DB Java 3.x Driver. I want to group my collection through the usernames, and sort the results by the count of results DESC.

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

Here is the shell query which I want to implement the Java equivalent:

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

The result I need is the count of documents grouped by username. countOfResults returns the total number of the documents the collection has.

推荐答案

您应尽量不要在Mongo 3.x中使用旧对象(BasicDBObject)类型.您可以尝试这样的事情.

You should try not to use old object (BasicDBObject) types with Mongo 3.x. You can try something like this.

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驱动程序-按查询分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆