Create Conditional TTL in Mongo

There is a special task that I want to accomplish, but I do not find any concrete way to do this. Suppose I have an application that is used to send letters. I continue to write these letters in collections in mongo. And using this application, I can send mail right now or schedule mailings for the future. The structure of the documents in the collection is similar:

{
'_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
}

The scheduleDate field can be null or any, depending on whether it is scheduled or not. I do not want to store data older than 2 days, so I created a TTL index on 'createdDate' for 2 days. But I also do not want to delete rows or queries planned for the future. I was looking for some conditional TTL, but could not find such a solution.

- , , TTL itin mongodb.

TTL, :

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

, , .

EDIT: , requestDate .

+5
4

MongoDB 3.2, TTL, . , , :

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

, partialFilterExpression : https://docs.mongodb.com/manual/core/index-partial/

+5

. :

{
'_id' : 123456789,
'createdDate' '<date when mail was sent or the request was created>',
'scheduledDate' : '<time for which mail is scheduled>'
'expires': '<Date or NULL>'
}

TTL 0 expires. TTL .

Mongoose (ORM Node), , :

expires 'created date + 2 days'.

{
  type: Date,
  default: function() { 
    return new Date(Date.now() + 1000*60*60*24*2);
  }
}

:

myNewDocument.expires = new Date( scheduled + ... );

, :

function() {
    if(this.get("type") === 2) {
      return scheduled_date_plus_2_days;
    } else {
      return created_date_plus_2_days;
    }
}

NULL:

myNewDocument.expires = null;

, , , .. , expires NULL .
, , expires.

+8

TTL scheduledDate, , . , , () , .

Mongo 3.2 , , :

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} )

new Date() ,

+2
source
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let PassWordReSate = new Schema(
  {
    hex: String,
    email: String,
  },
  {
    collection: "PassWordReSate",
    timestamps: true,
  }
);
PassWordReSate.path("createdAt").index({ expires: 6 });
module.exports = mongoose.model("PassWordReSate", PassWordReSate);
0
source

Source: https://habr.com/ru/post/1627156/


All Articles