Mongo DB Java 3.x 驱动程序

编程入门 行业动态 更新时间:2024-10-27 16:34:17
本文介绍了Mongo DB Java 3.x 驱动程序 - 按查询分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 代码:

Here is the Java code that I have implemented:

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 驱动程序

本文发布于:2023-11-22 12:54:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617492.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:驱动程序   DB   Mongo   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!