Angel Todorov
Angel Todorov

Reputation: 1533

Mongodb, mongoose - dynamically set TTL time

I am referring to this Time to live in mongodb, mongoose dont work. Documents doesnt get deleted to ask my question: Is it possible to set TTL time for MongoDB dynamically? So let's suppose you have token collection and you want to use it for different purposes. In that case every time when you create the token it would be nice to set specific TTL for each token. If this is possible, could you please provide some code snippet?

Upvotes: 3

Views: 5256

Answers (2)

Abhishek Biswal
Abhishek Biswal

Reputation: 450

To dynamically set a TTL to a document you can make use of the same index, but create another field like expireAt in the schema like:

expireAt: {
            type: Date,
            default: null,
}

Then create an index like (example for mongoose):

schema.index({ expireAt: 1 }, { expireAfterSeconds: 0 });

Now for all documents that you want to expire, you can set the exact datetime. For others, whose field expireAt is defaulting to null won't expire.

You can see the same example here in MongoDB Docs.

Upvotes: 7

Disposer
Disposer

Reputation: 6371

If you define a TTL index on a collection, then periodically MongoDB will remove() old documents from the collection.

db.events.ensureIndex('time', expireAfterSeconds=3600)

It use an indexing system for handling TTL. Its fixed, there is no way to define it dynamically for each document. in your scenario I recommend you to use Messaging System like RabbitMQ along with MongoDB https://www.rabbitmq.com/ttl.html

Upvotes: 1

Related Questions