15

I am looking into deleting a document at a specific time.

const TestSchema = new Schema({
 expire_at: {
 type: Date,
 },
}, {
 timestamps: true,
});
TestSchema.index({expire_at: 1}, {expireAfterSeconds: 0});

POST

const test = new TestSchema(this.request.body);
  test.expire_at = test.end_time;

  try {
    yield test.save();
  } catch (error) {
    this.status = 409;
    this.response.body = error.errors;
    return;
  }

  this.response.body = test;
  this.status = 201;

It does not seem that the documents delete at the time specified in expire_at.

I am using this Date format: 2016-07-20T05:01:19.567Z

safaiyeh
  • 1,655
  • 3
  • 16
  • 35

6 Answers6

45

This will delete the document in two hours:

const TestSchema = new Schema({
    expire_at: {type: Date, default: Date.now, expires: 7200} 
})

//expired in 2 hours
emilioriosvz
  • 1,629
  • 1
  • 19
  • 30
  • 2
    Thank you! This worked. I tried a lot of variations and combinations, including the same exact pattern with 'createdAt', however, never worked. Yet this worked! – danefondo Oct 16 '20 at 11:08
14

To delete MongoDB document in specific time you can use TTL (time to live). TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time.

So you need to create a TTL index like: (mongo shell command)

db.yourCollecName.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );

or you can use mongoose to create this index

TestSchema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 5 } );

then mongodb check after every 60 second and if expire_at date time is less than the current date time then this record will remove after 5 second.

The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database.

The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.

TTL Indexes

NB: Use createIndex instead of index

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
5

Deletion process runs after 60 seconds. So document can be there for 59 seconds after the deletion time has been passed.

Amit
  • 145
  • 3
  • 11
3

As Amit noted, TTL Indexes are not guaranteed to delete data at the time of expiration; the background task to expire data will run every 60 seconds.

The background tasks can also be affected by performance contention and workload, which can cause data to exist far beyond this window:

The background task that removes expired documents runs every 60 seconds. As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.

Because the duration of the removal operation depends on the workload of your mongod instance, expired data may exist for some time beyond the 60 second period between runs of the background task.

Source

Adam Harrison
  • 3,323
  • 2
  • 17
  • 25
0
const otpSchema = new mongoose.Schema({
   
    // other fields

    // expiry date of the document
    expire_at: {
        type: Date,
        default: Date.now(),
        expires: 60
    }
}, { timestamps: true })

otpSchema.index({ "expire_at": 1 }, { expireAfterSeconds: 5 });

This thing worked for me while using mongoose. Just add an extra field with title 'expire_at' and add the index to the schema. Rest everything will be managed by mongodb itself.

  • do u know of any way to make the expiration time dynamic in my app i want to control the expiration time of document but setting a hardcoded value will not work for me pls reply – Code Fingers Jun 29 '22 at 14:17
  • @CodeFingers I don't think there is any such option in MongoDB as the dynamic expiry time. Probably you can do it by implementing functionality in your backend server. You may specify here about what you want to build if you need any help. – Dhiraj Narsinghani Jul 07 '22 at 02:33
0

To delete a collection from DB do like bellow. I am using MongoDB 4.4 and Its working fine. For MongoDB drivers: db.collectionName.createIndex({createdAt:1},{expireAfterSeconds:5}) For Mongoose: collectionName.createIndex({"createdAt": 1 }, { expireAfterSeconds: 5 } )

AL Mahmud
  • 113
  • 2