MongoDB Java driver: distinct with sort

余生长醉 提交于 2019-12-04 23:29:45

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/18326345/mongodb-java-driver-distinct-with-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!