Complex sorting using mongodb?


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.

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

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

Then, you could have a route to fetch this.

def view_all_articles():
  articles = [ 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.