【问题标题】:how can I use ttl (time to live) on mongodb with collection.update?如何通过 collection.update 在 mongodb 上使用 ttl(生存时间)?
【发布时间】:2025-12-30 21:20:23
【问题描述】:

我想使数据库中的数据过期(它可以与 expireAfterSeconds 一起使用),但我想使用 collection.update>> 数据总是实时发送数据到数据库,所以 TTL 必须处理更新数据.. 可以我这样做??

这是我的代码,用于在指定时间后使用 ttl 从 mongodb 中删除数据。

var time = "20";


MongoClient.connect(url, function(err, db) {
  if (err) throw err;
    var dbase = db.db("testing5");
var myobj = ({ 
    "email" : scream_email,
     "location_id" : location ,
      "trend_tags" :trends ,
      "language" : lang , 
      "createdAt" : new Date(),
      "emoji" : emoji,
       "scream_link" : scream_path , 
       "scream_type" : screamtype
     });

dbase.collection("log_events").ensureIndex({ "email": 1 }, { expireAfterSeconds: time ,unique:true})


  dbase.collection("log_events").insertOne(myobj, function(err, result) {
    if (err) throw err;
    resultant = result

    console.log("data inserted and will be deleted approximately after 20 seconds");
    db.close();
  });
  });

【问题讨论】:

  • 我使用 azure mongo DB 进行使用。它有一个配置来定义可能包含日期时间值的字段。 Db 将从数据库中读取 expireafterseconds 的值并检查文档中的日期时间值字段。因此它工作正常。

标签: javascript node.js mongodb


【解决方案1】:

来自TTL Index manual

要创建 TTL 索引,请在其值为日期或包含日期值的数组的字段上使用带有 expireAfterSeconds 选项的 db.collection.createIndex() 方法。

但是您的索引创建使用email,我认为它不包含任何日期:

...ensureIndex({ "email": 1 }, { expireAfterSeconds: time ,unique:true})

相反,您需要使用 createdAt 字段来使 TTL 索引起作用,我假设它包含文档的创建时间:

...createIndex({ "createdAt": 1 }, { expireAfterSeconds: time })

此外,您不希望索引上的unique: true 约束。否则,数据库将不允许同时插入两个文档。

更多示例请查看Expire Data from Collections by Setting TTL

请注意,ensureIndex() 是一个古老的 MongoDB 习语,是 deprecated since MongoDB 3.0。请改用db.collection.createIndex()

【讨论】: