Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

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));

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

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

like image 219
Ken Liu Avatar asked Aug 20 '13 03:08

Ken Liu


1 Answers

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.

To do the equivalent in Java you would do:

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

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.

like image 158
JohnnyHK Avatar answered Sep 18 '22 12:09

JohnnyHK