Remove all Duplicates except the most recent document
<p>I would like to clear all duplicated of a specific field in a collection. leaving only the earliest entry of the duplicates.</p>

<p>Here is my aggregate query which works great for finding the duplicates:</p>

<pre><code>db.History.aggregate([
  { $group: {
_id: { name: "$sessionId" },  
uniqueIds: { $addToSet: "$_id" },
count: { $sum: 1 } 
  } }, 
  { $match: { 
count: { $gte: 2 } 
  } },
  { $sort : { count : -1} }
 ],{ allowDiskUse:true,
  cursor:{}});
</code></pre>

<p>Only problem is that i need to execute a remove query as well and keep for each of the duplicates the youngest entry (determined by the field 'timeCreated': </p>

<pre><code>"timeCreated" : ISODate("2016-03-07T10:48:43.251+02:00")
</code></pre>

<p>How exactly do i do that?</p>