title: How do I find the latest record(s) in a mongo query?
body: <p>Suppose my collection <code>c</code> has records like this:</p>
  
  <pre><code>{ "_id": ..., "name":"foo", "date": "2020-02-02 ...", "value": 10 ...}
  </code></pre>
  
  <p>and I want to find, for each <code>name</code>, the <em>latest</em> (by <code>date</code>) record with a positive <code>value</code>.</p>
  
  <p>Something like</p>
  
  <pre class="lang-py prettyprint-override"><code>def find_latest():
      res = {}
      for d in c.find({"value":{"$gt":0}}):
          key = d["name"]
          try:
              if d["date"] &gt; res[key]["date"]:
                  res[key] = d
          except KeyError:
              res[key] = d
      return res
  </code></pre>
  
  <p>but the loop should be on the server side.</p>
  
  <p>I suspect that it should be doable using <a href="https://api.mongodb.com/python/current/examples/aggregation.html" rel="nofollow noreferrer">aggregation</a> but it appears that I would need to write JavaScript for that...</p>