HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Is there any way to efficiently perform the equivalent of DENSE_RANK in MongoDB?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
efficientlytheequivalentanymongodbwayperformdense_rankthere

Problem

SQL Server and Oracle both have DENSE_RANK functions. Is there a way to do something similar in MongoDB without having to resort to MapReduce? In other words, suppose you have a T-SQL select clause like this:

SELECT DENSE_RANK() OVER(ORDER BY SomeField DESC) SomeRank


What is the best way to do the same thing in MongoDB?

(Note: This is a repost of the MongoDB question over here. I'm hoping to get more feedback from DBAs...)

Solution

MongoDB doesn't have any concept of ranking. The closest I could find comes from here:

Here's some sample data:

> db.scoreboard.find()`
 { "_id" : ObjectId("4d99f71450f0ae2165669ea9"), "user" : "dave", "score" : 4 }
 { "_id" : ObjectId("4d99f71b50f0ae2165669eaa"), "user" : "steve", "score" : 5 }`
 { "_id" : ObjectId("4d99f72350f0ae2165669eab"), "user" : "tom", "score" : 3 }


First, find the score of the user "dave":

db.scoreboard.find({ user : "dave" }, { score : 1 }) { "_id" : ObjectId("4d99f71450f0ae2165669ea9"), "score" : 4 }


Then, count how many users have a higher score:

db.scoreboard.find({ score : { $gt : 4 }}).count() 
 1


Since there is 1 higher score, dave's rank is 2 (just add 1 to the
count of higher scores to get the rank).

Obviously, this is far from ideal. However, MongoDB simply does not have any type of functionality for this since it's simply not designed for this type of querying.

Code Snippets

> db.scoreboard.find()`
 { "_id" : ObjectId("4d99f71450f0ae2165669ea9"), "user" : "dave", "score" : 4 }
 { "_id" : ObjectId("4d99f71b50f0ae2165669eaa"), "user" : "steve", "score" : 5 }`
 { "_id" : ObjectId("4d99f72350f0ae2165669eab"), "user" : "tom", "score" : 3 }
db.scoreboard.find({ user : "dave" }, { score : 1 }) { "_id" : ObjectId("4d99f71450f0ae2165669ea9"), "score" : 4 }
db.scoreboard.find({ score : { $gt : 4 }}).count() 
 1

Context

StackExchange Database Administrators Q#4859, answer score: 5

Revisions (0)

No revisions yet.