I. Introduction to TTL Indexes

The TTL index can set the expiration attribute for single column values to automatically delete documents after expiration

Limit of TTL index

The TTL index cannot be used or does not take effect in the following cases:

  • If the index field is not of the date type, the TTL index does not take effect
  • If the value of the index field is null or there is no index field, the TTL index does not take effect
  • A TTL index supports only single-field indexes, but a compliance index does not
  • The _ID field does not support the TTL index
  • You cannot create a normal index and a TTL index on the same field at the same time (a TTL index is essentially a normal index with an expired attribute configuration)
  • If you want to create a TTL index for a field that already has a common index, delete the common index first

3. Implementation principle of TTL index

  • MongoDB starts a thread in the background, which triggers a deletion task every 60 seconds to delete expired documents

1. If the amount of data is large, the data may not be deleted in time after expiration. Therefore, THE TTL index is not applicable to scenarios that have strict requirements on time

2, should try to avoid data at the same time in a centralized expiration

  • In the mongoDB replica, the TTL thread thread is only started at the primary node, and the data to be deleted from the secondary node is synchronized from the oplog log of the primary node

4. Use of TTL index

1. Specify an expiration time when creating an index

db.collectionName.createIndex({
    "deadlineDate": 1
}, {
    expireAfterSeconds: 3600
});
Copy the code
  • ExpireAfterSeconds Specifies an index expiration time of 3600s

  • Insert data, and the data will expire around 3600s after insertion

    db.collectionName.insert({
       "deadlineDate": new Date(),
       "age": 24."name": "liuqiuyi"
    });
    Copy the code

2. Specify the expiration time when inserting data

db.collectionName.createIndex({
    "deadlineDate": 1
}, {
    expireAfterSeconds: 0
});
Copy the code
  • ExpireAfterSeconds is set to 0

  • Insert data, specifying the expiration time through the data’s deadlineDate field

    db.collectionName.insert({
       "deadlineDate": ISODate("The 2020-12-21 T11:46:42. 477 z"),
       "age": 24."name": "liuqiuyi"
    });
    Copy the code

    The document will be deleted automatically at 2020-12-21 11:46:42

3. Modify the TTL index

// Change the index definition to change the document expiration time to 60 seconds
db.runCommand( { collMod: "collectionName",
			index: { keyPattern: { deadlineDate: 1 },
			expireAfterSeconds: 60
			}
Copy the code