简体   繁体   中英

MongoDB TTL index never deletes records

I created an index as shown below and added a createdAt field to each new record added to the db. The records should be auto-deleted after 24 hours however I have waited days and nothing has been deleted.

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

Adding record to the database

// Add info to db to search
    console.log("Adding info to database..");
    const otherAddress = e.target.address.value;
    const newRecord = {
        holderAddress: this.props.account,
        otherAddress: otherAddress,
        date: new Date(),
        data: encryptedData
    }
    await fetch("http://localhost:420/record/add", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(newRecord),
    }).catch(error => {
        window.alert(error);
    });

Endpoint it calls:

recordRoutes.route("/record/add").post(function (req, response) {
let db_connect = dbo.getDb();
let myobj = {
    holderAddress: req.body.holderAddress,
    otherAddress: req.body.otherAddress,
    data: req.body.data,
    createdAt: req.body.date
};
db_connect.collection("records").insertOne(myobj, function (err, res) {
    if (err) throw err;
    response.json(res);
});

Below is a screenshot from MongoDB website confirming there is an index..

在此处输入图像描述

Output from: db_connect.collection("records").stats().then(r => { console.log(r)});

 createdAt_1: {
  metadata: [Object],
  creationString: 'access_pattern_hint=none,allocation_size=4KB,app_metadata=(formatVersion=8),assert=(commit_timestamp=none,durable_timestamp=none,read_timestamp=none,write_timestamp=off),block_allocation=best,block_compressor=,cache_resident=false,checksum=on,colgroups=,collator=,columns=,dictionary=0,encryption=(keyid=,name=),exclusive=false,extractor=,format=btree,huffman_key=,huffman_value=,ignore_in_memory_cache_size=false,immutable=false,import=(enabled=false,file_metadata=,repair=false),internal_item_max=0,internal_key_max=0,internal_key_truncate=true,internal_page_max=16k,key_format=u,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=16k,leaf_value_max=0,log=(enabled=false),lsm=(auto_throttle=true,bloom=true,bloom_bit_count=16,bloom_config=,bloom_hash_count=8,bloom_oldest=false,chunk_count_limit=0,chunk_max=5GB,chunk_size=10MB,merge_custom=(prefix=,start_generation=0,suffix=),merge_max=15,merge_min=0),memory_page_image_max=0,memory_page_max=5MB,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=true,prefix_compression_min=4,readonly=false,source=,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,tiered_object=false,tiered_storage=(auth_token=,bucket=,bucket_prefix=,cache_directory=,local_retention=300,name=,object_target_size=10M),type=file,value_format=u,verbose=[],write_timestamp_usage=none',
  type: 'file',
  uri: 'statistics:table:index-3854-9052224765860348301',
  LSM: [Object],
  'block-manager': [Object],
  btree: [Object],
  cache: [Object],
  cache_walk: [Object],
  'checkpoint-cleanup': [Object],
  compression: [Object],
  cursor: [Object],
  reconciliation: [Object],
  session: [Object],
  transaction: [Object]
}

Any help is greatly appreciated!

Expiration of data requires that the indexed field value be a BSON date, or an array of BSON dates.

MongoDB Reference Manual " target="_blank">MongoDB 参考手册-->

Expiration of Data
TTL indexes expire documents after the specified number of seconds
has passed since the indexed field value; i.e. the expiration threshold
is the indexed field value plus the specified number of seconds.

If the field is an array, and there are multiple date values in the index,
MongoDB uses lowest (i.e. earliest) date value in the array to calculate
the expiration threshold.

If the indexed field in a document is not a date or an array that holds
one or more date values, the document will not expire.

If a document does not contain the indexed field, the document will not
expire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM