MongoDB Java驱动程序:与sort不同

编程入门 行业动态 更新时间:2024-10-28 21:25:55
本文介绍了MongoDB Java驱动程序:与sort不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用MongoDB控制台我可以使用不同的密钥编写本地MongoDB查询,其类似于:

Using the MongoDB console I can write a native MongoDB query using distinct key with a sort like this:

db.mycollection.distinct('mykey').sort('mykey', 1)

使用Java驱动程序I我希望能够像这样编写相同的查询:

Using the Java driver I would expect to be able to write the same query like this:

myCollection.distinct("myKey").sort(new BasicDBObject("myKey", 1));

然而,这不起作用,因为 DBCollection#distinct()返回类型列表而不是键入 DBCursor 如 DBCollection#find() 。

However, this doesn't work because DBCollection#distinct() returns type List and not type DBCursor like DBCollection#find().

如何使用Java驱动程序编写带有排序的不同查询?

How can I write the distinct query with a sort using the Java driver?

推荐答案

MongoDB不支持使用 distinct 进行服务器端排序命令。控制台中发生的事情是 distinct('myKey')调用返回一个数组,然后你调用JavaScript sort 该数组的方法,它返回数组的排序版本。您传入 sort 的参数将被忽略。

MongoDB doesn't support server-side sorting with the distinct command. What's happening in the console is that the distinct('myKey') call returns an array and then you're calling the JavaScript sort method on that array which returns a sorted version of the array. The parameters you pass into sort are ignored.

要在Java中执行等效操作,您可以执行以下操作:

To do the equivalent in Java you would do:

List myKeys = myCollection.distinct("myKey"); java.util.Collections.sort(myKeys);

要使用服务器端排序获取唯一密钥,您可以使用聚合。以下是你在shell中的表现:

To get the unique keys using a server-side sort you could use aggregate. Here's how you'd do that in the shell:

db.mycollection.aggregate([ { $group: {_id: '$myKey' }}, { $sort: {_id: 1}} ])

然而,当我测试这个时,简单的客户端排序方法表现得更好。

However, when I tested this, the simple client-side sort approach performed much better.

更多推荐

MongoDB Java驱动程序:与sort不同

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

发布评论

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

>www.elefans.com

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