在mongo中创建条件TTL [英] Create a conditional TTL in mongo

查看:343
本文介绍了在mongo中创建条件TTL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想完成一个特定的任务,但是我没有找到任何特定的方法来完成该任务. 可以说我有一个用于发送邮件的应用程序.我将这些邮件的记录保存在mongo的一个集合中.使用此应用程序,我可以立即发送邮件,也可以安排将来的邮件. 集合中文档的结构如下:

There is a particular task I want to accomplish , but I am not finding any particular way to do that. Lets say I have an app that is used to send mails. I keep record of this mails in a collection in mongo. And using this app I can send mail right now or can schedule mails for future. The structure of documents in collection is like :

{
'_id' : 123456789,
'to_email' : 'xyz@gmail.com'
'from_email' : 'abc@gmail.com'
'subject': 'some subject'
'type' : '<1 if normal and 2 if scheduled>',
'createdDate' '<date when mail was sent or the request was created>',
'scheduledDate' : '<time for which mail is scheduled>'
.. and many more key-value pairs
}

scheduledDate字段可以为零或任何日期,具体取决于其是否已计划. 我不想保留超过2天的数据,因此我在'createdDate'上创建了2天的TTL索引. 但是我也不想删除计​​划在将来使用的行或请求. 我正在寻找某种条件TTL,但找不到任何此类解决方案.

The scheduledDate field can be zero or any date, depending on if its scheduled or not. I dont want to keep data which is older than 2 days, so I created a TTL index on 'createdDate', for 2 days. But I also dont want to delete rows or requests which are scheduled for future. I was looking for some kind of conditional TTL, but couldnt find any such solution.

在mongodb中是否有可用的条件条件TTL或任何其他方式来实现它.

Is there anything available like conditional TTL or any other way to do itin mongodb.

我想创建一个像这样的TTL:

I want to create a TTL which work like :

if(requestType!=2 and createdDate < -2days)
delete row;

或者有一种方法可以使我使用任何语言对某些文档进行更改,以使它们不会过期.

or is there a way where I can make changes to certain documents using any language, so that they dont get expired.

我通过在Scheduled邮件中对ScheduledDate和requestDate使用相同的值来解决了这个问题.

EDIT : I solved this, by using same values for scheduledDate and requestDate in case of scheduled mails.

推荐答案

从MongoDB 3.2开始,也可以使用指定的过滤器表达式添加部分TTL索引.如果您只需要删除普通的非预定电子邮件,则可以使用以下内容:

As of MongoDB 3.2, it is also possible to add a partial TTL index using a specified filter expression. In case if you need to remove only normal not scheduled emails, you could use the following:

db.email.createIndex( {createdDate: 1}, {
    expireAfterSeconds: 172800, // 2 days
    partialFilterExpression: {
        scheduledDate: 0
    }
});

请注意,partialFilterExpression对可能的过滤条件有限制: https://docs .mongodb.com/manual/core/index-partial/

Note that partialFilterExpression has restrictions on possible filter conditions: https://docs.mongodb.com/manual/core/index-partial/

这篇关于在mongo中创建条件TTL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆