Complex sorting using mongodb?


#1

Inexperienced with mongodb. Imagine you have something like the sorting algorithm for Hacker News. On a python SQLAlchemy database, you might be able to use this in the database model.

@hybrid_method
def popularity(self, gravity=2):
  hours_ago = (self.timestamp - datetime.utcnow()).total_seconds() / 3600
  return (self.views - 1) / (hours_ago + 2) ** gravity

@popularity.expression
def popularity(self, gravity=2):
  hours_ago = func.extract('epoch', self.timestamp - func.now()) / 3600
  return (self.views - 1) / func.power((hours + 2), gravity)

Then, you could have a route to fetch this.

@articles.route('/')
def view_all_articles():
  articles = [x.read() for x in Article.query.order_by(Article.popularity().desc()).all()]
  return jsonify({'top': articles})

Can you do something similar in mongodb? It’s hard to normalize because it’s based on the current time accessed.