Ken*_*Liu 6 java sorting distinct mongodb
使用MongoDB控制台,我可以使用不同的密钥编写本机MongoDB查询,其类似于:
db.mycollection.distinct('mykey').sort('mykey', 1)
Run Code Online (Sandbox Code Playgroud)
使用Java驱动程序,我希望能够像这样编写相同的查询:
myCollection.distinct("myKey").sort(new BasicDBObject("myKey", 1));
Run Code Online (Sandbox Code Playgroud)
然而,这并不工作,因为DBCollection#distinct()返回一个类型List,而不是键入DBCursor类似DBCollection#find().
如何使用Java驱动程序编写带有排序的不同查询?
Joh*_*yHK 13
MongoDB不支持使用该distinct命令进行服务器端排序.控制台中发生的是distinct('myKey')调用返回一个数组,然后你sort在该数组上调用JavaScript 方法,该方法返回数组的排序版本.您传入的参数将sort被忽略.
要在Java中执行相同的操作,您可以:
List myKeys = myCollection.distinct("myKey");
java.util.Collections.sort(myKeys);
Run Code Online (Sandbox Code Playgroud)
要使用服务器端排序获取唯一密钥,您可以使用aggregate.以下是你在shell中的表现:
db.mycollection.aggregate([
{ $group: {_id: '$myKey' }},
{ $sort: {_id: 1}}
])
Run Code Online (Sandbox Code Playgroud)
但是,当我测试它时,简单的客户端排序方法表现得更好.