简体   繁体   English

MongoDB Java驱动程序:与sort不同

[英]MongoDB Java driver: distinct with sort

Using the MongoDB console I can write a native MongoDB query using distinct key with a sort like this: 使用MongoDB控制台,我可以使用不同的密钥编写本机MongoDB查询,其类似于:

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

Using the Java driver I would expect to be able to write the same query like this: 使用Java驱动程序,我希望能够像这样编写相同的查询:

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

However, this doesn't work because DBCollection#distinct() returns type List and not type DBCursor like DBCollection#find() . 但是,这不起作用,因为DBCollection#distinct()返回类型List而不是像DBCollection#find()那样输入DBCursor

How can I write the distinct query with a sort using the Java driver? 如何使用Java驱动程序编写带有排序的不同查询?

MongoDB doesn't support server-side sorting with the distinct command. MongoDB不支持使用distinct命令进行服务器端排序。 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. 在控制台中发生的事情是, distinct('myKey')调用返回一个数组,然后你在该数组上调用JavaScript sort方法,该方法返回数组的排序版本。 The parameters you pass into sort are ignored. 传递给sort的参数将被忽略。

To do the equivalent in Java you would do: 要在Java中执行等效操作,您可以:

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

To get the unique keys using a server-side sort you could use aggregate . 要使用服务器端排序获取唯一键,可以使用aggregate Here's how you'd do that in the shell: 以下是你在shell中的表现:

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

However, when I tested this, the simple client-side sort approach performed much better. 但是,当我测试它时,简单的客户端排序方法表现得更好。

You can actually use pure javascript 你实际上可以使用纯JavaScript

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

or pass a compare function for more elaborated sorting: 或传递比较函数以进行更精细的排序:

db.users.distinct('mykey').sort(function(a, b){return a >b})

Tested on robomongo 在robomongo上测试过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM