开发者

get Distinct Values with Sorted Data

开发者 https://www.devze.com 2023-02-06 04:25 出处:网络
I need a Query t开发者_运维技巧o get distinct keys with sorted on basis of score in Mongodb 1.6.5

I need a Query t开发者_运维技巧o get distinct keys with sorted on basis of score in Mongodb 1.6.5

I have records Like

{key ="SAGAR"
score =16
note ="test1"
}

{key ="VARPE"
score =17
note ="test1"
}

{key ="SAGAR"
score =16
note ="test2"
}

{key ="VARPE"
score =17
note ="test2"
}

I need a query which sorts all records on score and returns me distinct key.....


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.


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}); 


Using mongo shell v3.6.23

you can sort the data along with distinct values by using

db.test.distinct("key").sort();

you cant specify for which field you want to sort the result nor you can define the order.

eg: you cant use .sort({key:value}) here

the reason is that here sort() here is not the mongosh sort which is defined on cursor.

the distinct query returns javascript's Array.prototype, so you can use all instance methods on it

0

精彩评论

暂无评论...
验证码 换一张
取 消