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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With