title: MongoDB : How to make findAndModify returns the Last Updated Record
body: <p>I am new to Mongo DB and having trouble as it is behaving differently in different environments ( Dev , QA and  Production)</p>
  
  <p>I am using findAndModify to Update the Records in my MongoDB .</p>
  
  <p>There is a Job that runs daily which Updates /Inserts Data to Mongo DB , and i am using findAndModify to Update the Record .</p>
  
  <p>But what i observed is that the first record that is returned by  findAndModify  is different in Dev , QA and Production environemnts although the three environments are  having the same Data ??</p>
  
  <p>As per the Mongo DB  document , it states that findAndModify will modify the first document </p>
  
  <p>Currently this is my code :</p>
  
  <pre><code>BasicDBObject update = new BasicDBObject();
  update.append("$set", new BasicDBObject(dataformed));
  coll.findAndModify(query, update);
  </code></pre>
  
  <p>Please let me know how can i make sure that , the findAndModify returns the Last Updated Record , rather than depending upon un predictable behaviour ??</p>
  
  <p><strong>Edited Part</strong></p>
  
  <p>I am trying to use sort for my code but it is giving me compilation errors </p>
  
  <p><strong>coll.findAndModify(query,  sort: { rating: 1 }, update);</strong></p>
  
  <p>I have a field called as lastUpdated which is created using System.currentTimeMilis </p>
  
  <p>So can i use this lastUpdated as shown this way to get the Last Updated Record </p>
  
  <pre><code>coll.findAndModify(  query, 
      new BasicDBObject("sort", new BasicDBObject("lastUpdated ", -1)), 
      update);    
  </code></pre>