sparkle
sparkle

Reputation: 7400

Mongodb: Get documents sorted by a dynamic ranking

I have these documents:

{ "_id" : ObjectId("52abac78f8b13c1e6d05aeed"), "score" : 125494, "updated" : ISODate("2013-12-14T00:55:20.339Z"), "url" : "http://pictwittrer.com/1crfS1t" }
{ "_id" : ObjectId("52abac86f8b13c1e6d05af0f"), "score" : 123166, "updated" : ISODate("2013-12-14T00:55:34.354Z"), "url" : "http://bit.ly/JghJ1N" }

Now, i would like to get all documents sorted by this dynamic ranking:

ranking = score / (NOW - updated).abs

ranking is a float value where: - score is the value of scopre property of my document - the denominator is just the difference between NOW (when I'm executing this query) and updated field of my document

I'd want to do this because I want the old documents are sorted last

Upvotes: 0

Views: 2886

Answers (2)

Nikolay Manolov
Nikolay Manolov

Reputation: 105

I'm new to Mongodb and aggregation frameworks but considering the answer Tim B gave I came up with this:

db.coll.aggregate(
      { $project : {
                     "ranking" : { 
                                  "$divide" : ["$score", {"$subtract":[new Date(), "$updated"]}]
                                 }
                   }
      },
      { $sort : {"ranking" : 1}})

Using $project you can reshape documents to insert precomputed values, in your case the ranking field. After that using $sort you can sort the documents by rank in the order you like by specifying 1 for ascending or -1 for descending.

I'm sorry for the terrible code formatting, I tried to make it as readable as possible.

Upvotes: 2

Tim B
Tim B

Reputation: 41188

Look at the MongoDB aggregation framework, you can do a project to create the score you want and then a sort to sort by that created score.

http://docs.mongodb.org/manual/core/aggregation-pipeline/

http://docs.mongodb.org/manual/reference/command/aggregate/#dbcmd.aggregate

Upvotes: 0

Related Questions