title: Retrieve last document in a MongoDB using Pymongo and Flask
body: <p>I'm working on a Raspberry Pi project that collects weather measurements and stores them in a Mongo database like this:</p>
  
  <pre><code>{
      "_id": {
          "$oid": "577975c874fece5775117209"
      },
      "timestamp": {
          "$date": "2016-07-03T20:30:00.995Z"
      },
      "temp_f": 68.9,
      "temp_c": 20.5,
      "humidity": 50,
      "pressure": 29.5
  }
  </code></pre>
  
  <p>The data is going into the Mongo db just fine. Next, I'm trying to build a Flask-based dashboard that enables me to look at the recorded data. On one of the pages of the dashboard, I want to show the current recorded values, so what I need to do is pull out the last measurement and pass it to a flask template for rendering to the browser.</p>
  
  <p>I found a post here that said I could use:</p>
  
  <pre><code>data = db.measurements.find().limit(1).sort({"$natural": -1})
  </code></pre>
  
  <p>but natural doesn't seem to be a valid option for the call to <code>find</code>.</p>
  
  <p>This works:</p>
  
  <pre><code>measurement = mongo.db.measurements.find_one()
  </code></pre>
  
  <p>It pulls back one random measurement that I can then pass to the flask template, but how do I use sort to get the most recent one?</p>
  
  <p>I tried:</p>
  
  <pre><code>measurement = mongo.db.measurements.find_one().sort([("timestamp", -1)])
  </code></pre>
  
  <p>but that generates an attribute error: <code>AttributeError: 'dict' object has no attribute 'sort'</code></p>
  
  <p>I've also tried:</p>
  
  <pre><code>cursor = mongo.db.measurements.find().limit(1).sort({"timestamp": -1})
  </code></pre>
  
  <p>but that doesn't work either. </p>
  
  <p>I'm missing something here, can someone give me a quick, complete fix for this?</p>