Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the sort direction of a MongoDB TTL index matter?

In other words, is there a difference between

db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )

and

db.eventlog.createIndex( { "lastModifiedDate": -1 }, { expireAfterSeconds: 3600 } )

?

The docs do not seem to mention anything regarding this.

like image 441
Manuel Avatar asked Sep 16 '25 09:09

Manuel


1 Answers

It doesn't matter.

With a single field index - The order won't matter. If they are close together in ascending order, they will also be close together in descending order.

How TTL works

//find the expireAfterSeconds value from collection indexes
var expireAfterSeconds = db.eventlog.getIndexes().filter(function(i){
    return i.hasOwnProperty('expireAfterSeconds');
})[0].expireAfterSeconds;

// epoch time
var startTime = new Date(1970,0,1);
// end time
var endTime = new Date(Date.now() - expireAfterSeconds*3600);
db.eventlog.remove({lastModifiedDate: { $gt: startTime, $lte: endTime }});

Reference: ttl.cpp source

Full TTL explanation: http://hassansin.github.io/working-with-mongodb-ttl-index

like image 69
Valijon Avatar answered Sep 18 '25 08:09

Valijon