Question

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.....

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top