简体   繁体   中英

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?

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.

You can actually use pure 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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