Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get Distinct Values with Sorted Data

I need a Query to 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.....

like image 521
Sagar Varpe Avatar asked Jan 21 '11 13:01

Sagar Varpe


2 Answers

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.

like image 101
Stuart Avatar answered Oct 15 '22 23:10

Stuart


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}); 
like image 32
Andrew Orsich Avatar answered Oct 15 '22 23:10

Andrew Orsich