mongodb通过TTL实现数据过期清除

【MongoDB】数据的自动过期,TTL索引 在近期的工作中,使用了MongoDB来保存了一些日志数据,但是这些日志数据具有一定的时效性,也就是按照业务的需要,保存xx天即可,在超过了这个时间之后,需要删除过时的日志。按照之前的做法,可以使用定时任务,例如:Spring的定时器,xxl-job等工具,在每天凌晨的时候删除数据,这种方法虽然可行,但是需要额外的编码工作。那有没有一种方式能够简单的搞定过期数据的清理呢?当然,MongoDB提供了一种TTL索引的机制,可以非常方便的处理这种需求,下面是官方文档,有阅读能力的同学可以直接看这个文档。 阅读详情
// 设置过期时间
Calendar cal = Calendar.getInstance();
//10小时后过期
cal.add(Calendar.HOUR, 10);
flightSlotChange.setExpireAt(cal.getTime());
this.mongoTemplate.save(flightSlotChange, MONGODB_COLLECTION_NAME);

//生成集合expire_at索引 用于过去
db.集合名称.createIndex({ "expire_at": 1 }, { expireAfterSeconds: 0 })

 //查看集合索引
db.集合名称.getIndexes()

//删除集合索引
db.集合名称.dropIndex("索引名称")

`expireAfterSeconds`是MongoDB索引选项之一,用于设置文档的过期时间。

当你使用`expireAfterSeconds`选项创建索引时,MongoDB会为具有某个字段(通常是日期或时间戳)的文档自动设置一个过期时间。该选项的值表示从该字段的值开始计算的秒数。

假设你在一个集合中创建了一个带有`expireAt`字段的索引,并将`expireAfterSeconds`设置为3600(1小时)。当你插入一个文档并设置了过期时间后,MongoDB会自动删除该文档,一旦`expireAt`字段的值加上3600秒后超过了当前时间。

注意,在创建索引时,如果设置了`expireAfterSeconds: 0`,会立即删除具有过期时间的文档。

总结起来,`expireAfterSeconds`选项允许你为具有过期时间的文档自动设置过期时间,并在到达指定秒数后自动删除这些文档。

MongoDB TTL索引:自动清理过期数据的智能机制与配置技巧 TTL索引是MongoDB中一种特殊的单字段索引,允许文档在指定时间后自动过期删除。它主要用于会话数据、事件日志等时效性数据管理,基于B-Tree索引结构和后台TTLMonitor线程实现自动清理。创建时需指定时间字段和过期秒数,支持Date类型和整数时间戳。TTL索引配置灵活,可与稀疏索引结合使用,但不支持复合索引。适用于会话管理、日志系统、临时数据存储等场景,能显著简化应用层清理逻辑,提高系统可维护性。使用时需注意索引创建规范和时间字段类型限制。 阅读详情

相关推荐

MongoDB自动删除过期数据的方法(TTL索引)

前序: 最近由于公司业务需求,对于3个月前的过期数据需要进行删除动作,以释放空间和方便维护 本来想的是使用crontab写个脚本定时执行,但是看到Mongo本身就有自动删除过期数据的功能,所以还是用一下吧 这个方法就是使用TTL索引,后续我再写一个脚本定时删除的任务,关于TTL索引的更多使用实例,大家可以参考学习这篇文章:https://www.jb51.net/article/126810.htm 介绍: TTL索引是MongoDB中一种特殊的索引, 可以支持文档在一定时间之后自动过期删除,目前TTL索引只能在单字段上建立,并且字段类型必须是date类型或者包含有date类型的数组

MongoDB——索引属性之TTL索引(TTL Indexes)

目录一、MongoDB官网地址二、TTL索引(TTL Indexes)的概述2.1、TTL索引(TTL Indexes)的前提条件2.2、处理历史数据通常的做法2.3、MongoDB提供的做法2.4、TTL索引(TTL Indexes)的理解2.5、创建TTL索引(TTL Indexes)的语法2.6、修改TTL索引(TTL Indexes)过期时间的语法三、TTL索引(TTL Indexes)的使用约束四、创建TTL索引(TTL Indexes)的示例4.1、数据准备4.2、创建TTL索引4.3、查询数据

小志的博客 6303

【实战解析】Ubuntu双网卡冲突:如何解决同一网段下网关无法访问及上网问题

本文深入解析Ubuntu服务器双网卡配置在同一网段时引发的路由冲突问题,导致网关无法ping通及无法上网。通过分析路由表与Metric值原理,提供使用route命令调整优先级及修改Netplan配置文件的实战解决方案,确保主次路由明确,一劳永逸解决网络冲突。

f9g0h的博客 280

MongoDB中的TTL索引:自动过期数据的深入解析与使用方式

TTL索引是MongoDB中一种非常有用的功能,可以自动清理过期数据以保持数据库的高效运行。通过选择合适的字段、创建TTL索引、插入或更新文档以及监控和调整索引策略,我们可以更好地管理和维护MongoDB数据库中的数据。然而,在使用TTL索引时,需要注意其限制和考虑因素,并根据实际的应用场景和数据特点进行优化和调整。

码到三十五 2590

CC2340R5-OAD升级实战:从配置到调试的全流程解析

本文详细解析CC2340R5芯片的OAD(空中升级)全流程,涵盖环境配置、MCU-BOOT、OAD-BL和OAD-APP程序开发,以及内存布局和调试技巧。通过实战案例展示如何实现蓝牙设备的远程固件升级,提升开发效率和产品可维护性。

silver的专栏 1063

鸿蒙OS+UniApp文件上传实战:如何解决大文件分片上传的3大坑?

本文深入探讨鸿蒙OS与UniApp结合实现大文件分片上传的实战方案,重点解决分片策略设计、网络中断处理和进度管理三大技术难题。通过鸿蒙分布式特性与UniApp跨平台能力的结合,提供动态分片调整、断点续传和跨设备进度同步等优化方案,显著提升大文件上传成功率和用户体验。

weixin_29250403的博客 474

java mongodb ttl_Mongodb设置TTL索引自动清除数据与过期数据的方法

Mongodb通常会被用来存储缓存数据或大尺寸、低价值的数据,对于这些类型的数据,数据量往往非常大,如果不定期清理,不但会影响性能,也会浪费大量的系统资源。Mongodb其实可以像Redis一样设置数据的过期时间,TTL索引是MongoDB中一种特殊的索引,可以支持文档在一定时间之后自动过期删除,目前TTL索引只能在单字段上建立。当你在集合中某一个字段建立TTL索引后,后台会有一个单线程,通过不断...

weixin_42520580的博客 1235

[Vue][面试]谈谈你对MVC、MVP和MVVM的理解

谈谈你对MVC、MVP和MVVM的理解 答题思路:此题涉及知识点很多,很难说清楚,说透彻,因为MVC,MVP这些我们前端程序员自己甚至都没用过。但是恰恰反映了前端这些年从无到有, 从有到优的变迁过程,因此沿此思路回答将十分清除。 Web1.0时代 在web1.0时代,并没有前端的概念。开发一个web应用多数采用ASP.NET/Java/PHP编写,项目通常由多个aspx/jsp/php文件构成,每个文件中同时包含了HTML、CSS、JavaScript、C#/Java/PHP代码, 系统整体架构可能如下图所

你好,欢迎光临! 723

Mongodb - TTL(time to live)特性

TTL集合支持mongodb对存储的数据进行失效时间设置,经过指定的时间段后、或在指定的时间点过期,集合自动被mongod清除。这一特性有利于对一些只需要保存一定时间的数据信息进行存储,比如机器产生的事件数据、日志、会话信息等。 Mongodb使用TTL索引特性来实现TTL集合。TTL通...

chongdutuo9831的博客 189

CentOS7下Ollama部署全攻略:从安装到自定义端口配置(附国内加速技巧)

本文详细介绍了在CentOS7系统上部署Ollama的完整流程,包括环境准备、模型下载优化、服务化部署及端口配置等关键步骤。特别针对国内网络环境提供了加速安装方案和镜像源配置技巧,帮助开发者快速搭建稳定的本地AI运行环境。

mmm90的博客 289

基于相位检测与锁相环的DIY超声波风速仪设计与实现

相位检测是信号处理中的一项基础技术,它通过测量两个周期信号之间的相位差来获取信息。其核心原理在于,当信号在介质中传播时,外部因素(如风速)会改变其传播速度,从而导致接收端信号的相位发生偏移。锁相环(PLL)是实现高精度相位检测的关键电路,它能动态调整本地振荡器的频率,以跟踪并锁定输入信号的相位,从而将微小的相位变化转换为易于测量的电压信号。这项技术的工程价值在于其对电路精度要求相对较低,鲁棒性好,非常适合低成本、高灵敏度的测量应用。在气象监测、工业传感和消费电子等领域,相位检测技术被广泛用于风速风向测量、位

weixin_29540599的博客 387

(实战场景)关于MongoDB使用TTL索引进行自动删除表数据的教程

要在MongoDB中创建TTL索引,以自动删除基于CreateTime字段的指定时间之前的数据,并且要确保兼容低版本的MongoDB,你可以按照以下步骤进行操作。

qq_41308489的博客 1033

window系统 dlib库安装

1. 安装visual studio 1.1. 安装vs2017或以上版本 1.2. 我们需要安装使用C++的桌面开发,且必须选上用于Cmake的Visual C++工具 1.3. 安装完成后,将D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin 添加到环境变量PATH中 2 下载cmake文件,并添加环境变量 2.1 在c

@bangbang的博客 815

java mongodb ttl_Mongodb - TTL(time to live)特性

TTL集合支持mongodb对存储的数据进行失效时间设置,经过指定的时间段后、或在指定的时间点过期,集合自动被mongod清除。这一特性有利于对一些只需要保存一定时间的数据信息进行存储,比如机器产生的事件数据、日志、会话信息等。Mongodb使用TTL索引特性来实现TTL集合。TTL通过一个后台线程读取索引中数据类型的值,然后清除过期的集合。集合中的文档超过expireAfterSeconds关键...

weixin_28871885的博客 311

DLMS/COSEM协议的理解体会

DLMS是通信协议,COSEM是电表建模规范。HDLC帧基本格式为0x7e......

一个bug是bug,多个bug能work 8312

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ttl mysql_MongoDB 三大利器 TTL, Gridfs, MapReduce

一、 Time To Live(TTL) 集合MongoDB 2.2 引入一个新特性--TTL 集合,TTL集合支持失效时间设置,当超过指定时间后,集合自动清除超时文档,者用来保存一个诸如session会话信息的时候非常有用。如果想使用TTL集合,用用到 expireAfterSeconds 选项db.ttl.ensureIndex({ "date": new Date() }, { expire...

weixin_39687621的博客 327

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Mongoose 设置TTL(time to live) 过期自动删除数据

最近忙好忙。。。没什么时间积累,今天抽空赶紧随手记一个新操作 什么是TTL TTL(time to live) 集合支持mongodb对存储的数据进行失效时间设置,经过指定的时间段后、或在指定的时间点过期,集合自动被mongod清除。这一特性有利于对一些只需要保存一定时间的数据信息进行存储,比如机器产生的事件数据、日志、会话信息等。 简单场景 比如用户的验证码,生成后需要存在数据库的ver...

Creabine的博客 2482

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

MongoDB TTL索引:自动化数据清理实战指南

TTL(Time-To-Live)索引是MongoDB中用于自动化清理过期数据的核心机制,其原理是通过后台线程定期扫描日期类型字段,自动移除超过预设存活时间的文档。这种技术特别适用于物联网设备日志、用户会话管理等需要自动维护数据新鲜度的场景。从实现角度看,TTL索引通过设置expireAfterSeconds参数控制数据生命周期,同时支持动态调整不同文档的存活时间。在分片集群部署时,需要注意索引字段的选择以避免清理负载不均。结合监控指标如ttl.passes和deletedDocuments,可以有效优化清

weixin_34009794的博客 475

MongoDB 存活時間 TTL 用法

使用方法: db.Colloctions.ensureIndex({'date':1},{expireAfterSeconds:60})//date 为设置的索引,expireAfterSeconds为数据删除事件 MongoDB 透過mongod背景處理過期的資料https://docs.mongodb.com/manual/release-notes/2.2/,頻率為一分鐘一次。在建...

weixin_30686845的博客 360

MongoDB 三大利器 TTL, Gridfs, MapReduce [转]

文章转自 https://www.jianshu.com/p/b0e51059e773, 感谢作者分享 一、 Time To Live(TTL) 集合 MongoDB 2.2 引入一个新特性--TTL 集合,TTL集合支持失效时间设置,当超过指定时间后, 集合自动清除超时文档,者用来保存一个诸如session会话信息的时候非常有用。 如果想使用TTL集合,用用到 expireAfterSec...

fuckaholic的博客 515

MongoDB 学习笔记之 TTL索引,部分索引和文本索引

TTL索引: TTL集合支持mongodb对存储的数据进行失效时间设置,经过指定的时间段后、或在指定的时间点过期,集合自动被mongod清除。这一特性有利于对一些只需要保存一定时间的数据信息进行存储,比如机器产生的事件数据、日志、会话信息等。 先创建一个集合TTLCol: 创建TTL索引,60秒过期。 60秒后查询发现数据被删除了。 部分索引: Mong...

baguashenp74070的博客 160

MongoDB中TTL 索引一共包含哪些部分?使用场景是什么?底层原理是什么?

假设我们有一个简单的 PHP 程序,模拟 MongoDB 的 TTL 索引操作。通过以上内容,你应该已经对。

长风破浪会有时的博客 601
上一篇: Intellij IDEA 导入Maven项目
总妖怪要害朕丷
博客等级 码龄7年 0粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值