Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto deletion of documents from mongodb after specified time

Tags:

mongodb

I want to auto delete documents from a collection in mongodb based on a ttl. I have gone through other answers and figured out the following way:

db.collection.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

This will delete the documents after expireAfterSeconds interval from createdAt field.

However, the problem with above is that it is not document specific. In the above scenario, all documents will be deleted after 3600 time from creation. However, in my case, each document in the collection needs to be deleted at different time intervals. So, each document need to have its own ttl. How can I achieve this?

like image 622
weird_coder Avatar asked Nov 21 '18 16:11

weird_coder


People also ask

How do I delete a file in MongoDB after time?

TTL index. TTL (Time-To-Live) indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time. A background thread in mongod reads the values in the index and removes expired documents from the collection (usually every minute).

Why MongoDB data deleted automatically?

Answer is YES Mongodb is completely safe the reason behind this was the lack of security measures used by the programmers. You should only open the port of the server that are required example in Amazone web server (AWS) some programmers Open all the ports of security groups stop doing that.

What is TTL in MongoDB?

TTL Indexes indexes are single-field indexes that MongoDB can use to remove documents from a collection after a certain amount of time or at a specific clock time. You can specify the time expiration as expireAfterSeconds parameter.

Which of the following methods best helps to delete a document in MongoDB?

To delete a single document, use db. collection. deleteOne()


1 Answers

You can set specific time for each document for remove. Please check documentation https://docs.mongodb.com/manual/tutorial/expire-data/ under ‘Expire Documents at a Specific Clock Time’ capter

like image 145
andranikasl Avatar answered Oct 06 '22 02:10

andranikasl