get Distinct Values with Sorted Data

拥有回忆 提交于 2019-12-03 02:21:54

There is distinct command in mongodb:

you can use distinct like this:

db.test.distinct({"key":true,"score":true,"note":true}); 

the same in relational database:

SELECT DISTINCT key,score,note FROM test; 

And than sort result by adding following code:

.sort({score : 1}) // 1 = asc, -1 = desc

Total result will be like this:

 db.test.distinct({"key":true,"score":true,"note":true}).sort({score : 1}); 

You can use the aggregation framework to group by the element you want to be distinct (group makes it distinct). So if you wish to sort on score then get distinct keys you could do the following - sort by score, group by key and add score as arrays of elements (already sorted):

db.test.aggregate([
    { $sort : { score : -1 } },
    { $group : {_id : "$key", scores : { $push : "$score" } } }
])

This will result in distinct keys along with an array of scores which are those scores contained in the documents with duplicate keys. I'm not sure this is exactly what you're looking for and I know this is an old question but I thought this might help out someone else looking at it in the future - as an alternative way of doing this.

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