get Distinct Values with Sorted Data

Sagar Varpe picture Sagar Varpe · Jan 21, 2011 · Viewed 32.5k times · Source

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

Answer

Stuart picture Stuart · Aug 11, 2014

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.