MongoDB Java driver: distinct with sort -


using mongodb console can write native mongodb query using distinct key sort this:

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

using java driver expect able write same query this:

mycollection.distinct("mykey").sort(new basicdbobject("mykey", 1)); 

however, doesn't work because dbcollection#distinct() returns type list , not type dbcursor dbcollection#find().

how can write distinct query sort using java driver?

mongodb doesn't support server-side sorting distinct command. what's happening in console distinct('mykey') call returns array , you're calling javascript sort method on array returns sorted version of array. parameters pass sort ignored.

to equivalent in java do:

list mykeys = mycollection.distinct("mykey"); java.util.collections.sort(mykeys); 

to unique keys using server-side sort use aggregate. here's how you'd in shell:

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

however, when tested this, simple client-side sort approach performed better.


Comments

Popular posts from this blog

java - How to Configure JAXRS and Spring With Annotations -

visual studio - TFS will not accept changes I've made to a Java project -

php - Create image in codeigniter on the fly -