title: How fetch latest records using find_one in pymongo
body: <p>I have an existing program where I'm trying to fetch last inserted document which matches the key <code>aws_account_id</code> using <code>find_one</code> in pymongo.</p>
  
  <p>I'm using this query to perform the fetching:</p>
  
  <pre><code>report = securitydb.scout.find_one({'aws_account_id': aws_account.account_number})
  </code></pre>
  
  <p>But this query returns a wrong document. The image below demonstrates the expected result and the wrong one that I'm getting.</p>
  
  <p><a href="https://i.stack.imgur.com/rUtYm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rUtYm.png" alt="enter image description here"></a></p>
  
  <p>In the image, both documents have the same aws_account_id but the red one is inserted last. So the expected result is the red marked document but it pulls the yellow marked document.</p>
  
  <p>I'm not sure if I need to use sorting or things like that. I got some solution but those are based on pure mongo query. I need help doing this with pymongo.</p>
  
  <p>Thanks In Advance,
  Robin</p>