Create a conditional TTL in mongo

后端 未结 4 1823
你的背包
你的背包 2021-02-06 03:05

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 thes

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 03:33

    You can just create a TTL index on scheduledDate, if the value is zero it will not be deleted. According to the documentation, if the indexed field in a document is not a date or an array that holds a date value(s), the document will not expire.

    Using Mongo 3.2 I have verified this is indeed the case using this test collection:

    db.data.drop()
    db.data.save({scheduledDate: 0})
    db.data.save({scheduledDate: new Date()})
    db.data.save({scheduledDate: new Date()})
    db.data.createIndex( { "scheduledDate": 1 }, { expireAfterSeconds:1} )
    

    When using this collection all new Date() entries get removed , whereas the first record with the zero value remains

提交回复
热议问题