In the course of work, we will inevitably encounter such problems, we want to save some data, but we do not have a high demand for these data, sometimes just want to a certain time range of data, such as if we always only care about from the current time to push forward the data characteristics of six months, Then we don't need to save all the data, because not only is the disk space wasted, but other performance is also affected as the amount of data accumulates.
At this time we urgently need to be able to automatically when we insert data to help us to delete the data we do not want for some time, then how to achieve it?
Inside MongoDB, there is a special index, called the TTL index, through which the above functions can be implemented. What's the TTL index? How do I create a TTL index?
The TTL index is a special index that currently only supports indexing on a single field, and that field must be a date type or an array type that contains a date type. We can create a TTL index by using the CreateIndex method, as follows:
[JavaScript]View PlainCopy
- Db.collection.createIndex ({"Createtime": 1},{expireafterseconds:60});
Set the Expireafterseconds to control the expiration of the document, followed by the number of seconds Oh! In fact, that is, MongoDB in the background a thread constantly to query and delete outdated documents.
How do I implement the data time-out auto-deletion feature in MongoDB?