title: Delete mongo recored by the timestamp in its id
body: <p>This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its <code>_id</code>. I do not have any <code>date</code>, <code>createdAt</code> fields as <a href="https://docs.mongodb.com/manual/reference/method/ObjectId.getTimestamp/" rel="nofollow noreferrer">I see</a> that mongo uses its <code>_id</code> for the createdAt timestamp.</p>
  
  <p>How do I delete a recored, say created 30 days ago, using this <a href="https://gist.github.com/Stoffo/fd4a0a70be89e8d7ce15" rel="nofollow noreferrer">gist</a>?</p>
  
  <pre><code>const date = new Date();
  const daysToDeletion = 30;
  const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));
  
  const db = &lt;your-database&gt;
  
  db.messages.remove({_id : {$lt : deletionDate}});
  </code></pre>
  
  <blockquote>
    <p>The above returns a <code>CastError</code></p>
  </blockquote>
  
  <p>What would work, and as Ive said, I do not have a createdAt field:</p>
  
  <pre><code>db.messages.remove({createdAt : {$lt : deletionDate}});
  </code></pre>