MongoDB Java驱动程序:与sort不同 [英] MongoDB Java driver: distinct with sort

查看:331
本文介绍了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不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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