mongodb set automatic expiration

In business scenarios, this situation may occur: for example, only the records of the most recent period of time need to be saved, and the data beyond this time limit is invalid and can be deleted, otherwise the data will increase. The easiest way to think of is to set a script to run regularly to delete the data that exceeds the time. 

For mongodb, it comes with this function, which can set expired data to be automatically deleted.

How to create it, in fact, there is an options option when creating an index, which can specify the expiration time

db.collection.createIndex(keys, options)


However, not all fields can create such an index. The field field is either a date field or an array with a date field. Guess that its internal implementation actually judges the expiration by comparing this date.

See a simple example:

db.collection.createIndex({'create_time': 1}, {expireAfterSeconds: 3600})

In this way, the data inserted into this collection will be automatically cleared after an hour, and no manual processing is required. 



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325720478&siteId=291194637