Create a conditional TTL in mongo
<p>There is a particular task I want to accomplish, but I am not finding any particular way to do that.
Let's say I have an app that is used to send mails. I keep a record of these emails in a collection in mongo. And using this app I can send mail right now or can schedule emails for future.
The structure of documents in collection is like :</p>
<pre><code>{
'_id' : 123456789,
'to_email' : 'xyz@gmail.com'
'from_email' : 'abc@gmail.com'
'subject': 'some subject'
'type' : '&lt;1 if normal and 2 if scheduled&gt;',
'createdDate' '&lt;date when mail was sent or the request was created&gt;',
'scheduledDate' : '&lt;time for which mail is scheduled&gt;'
.. and many more key-value pairs
}
</code></pre>
<p>The <code>scheduledDate</code> field can be zero or any date, depending on if it's scheduled or not.
I don't want to keep data which is older than 2 days, so I created a TTL index on 'createdDate', for 2 days.
But I also don't want to delete rows or requests which are scheduled for the future.
I was looking for some kind of conditional TTL, but couldn't find any such solution.</p>
<p>Is there anything available like conditional TTL or any other way to do it in MongoDB.</p>
<p>I want to create a TTL which work like :</p>
<pre><code>if(requestType!=2 and createdDate &lt; -2days)
delete row;
</code></pre>
<p>or is there a way where I can make changes to certain documents using any language so that they don't get expired.</p>
<p>EDIT: I solved this, by using the same values for <code>scheduledDate</code> and <code>createdDate</code> in case of scheduled emails.</p>