我怎样才能在MongoDB上使用TTL(时间生活)与collection.update



我想使数据库中的数据过期(过期后秒可以(,但我想与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();
  });
  });

来自 TTL 索引手册:

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

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

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

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

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

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

有关更多示例,请参阅通过设置 TTL 使集合中的数据过期。

请注意,ensureIndex()是一个旧的MongoDB习惯用法,自MongoDB 3.0以来已被弃用。请改用 db.collection.createIndex((。

最新更新