【问题标题】:MongoDB expireAfterSeconds doesn't remove documentsMongoDB expireAfterSeconds 不会删除文档
【发布时间】:2016-01-29 12:52:17
【问题描述】:

我希望 MongoDB 在 % 秒过后清除其集合中的数据。我正在设置索引,但是一段时间后集合没有被清除,所有文档仍然存在。

我做错了什么?

数据库版本:3.2

设置索引:

 db.collection('history').ensureIndex(
   { '_id': 1, 'created': 1 },
   { unique: true, background: true, w: 1, expireAfterSeconds: 60}
 );

// or

 db.collection('history').createIndex(
   { '_id': 1, 'created': 1 },
   { unique: true, background: true, w: 1, expireAfterSeconds: 60}
 );

// history document
var _history = {
  _id: new ObjectId(),
  created: new Date()
};

收藏历史,索引:

var historyCollectionIndex = [
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "guardian_dev.history"
    },
    {
        "v" : 1,
        "unique" : true,
        "key" : {
            "_id" : 1,
            "created" : 1
        },
        "name" : "_id_1_created_1",
        "ns" : "guardian_dev.history",
        "background" : true,
        "expireAfterSeconds" : 60
    }
]

与创建索引有关的其他问题。

现在,可能会发生两个条目具有相同的创建值,因此,mongo 现在抛出 E11000 重复键错误收集错误。

是否可以添加 created 和 expireAfterSeconds,但 created 不一定是 uniq?

【问题讨论】:

  • 问题的第二部分:设置唯一性:false

标签: javascript node.js mongodb


【解决方案1】:

根据MongoDB site

TTL 索引是单字段索引。复合索引不支持 TTL 属性。

如果您删除 _id: 1 索引而只使用 created,那么它的行为应该与您预期的一样

【讨论】:

    【解决方案2】:

    根据documentation,TTL索引是单字段索引。复合索引不支持 TTL 属性。您应该按如下方式创建索引:

    db.collection('history').ensureIndex(
    {'created': 1 },
    { unique: true, background: true, w: 1, expireAfterSeconds: 60}
    );
    

    我已经对其进行了测试,并且该索引与您问题中的索引不同,它可以正确清除记录。

    【讨论】:

      猜你喜欢
      • 2018-11-05
      • 2013-09-14
      • 2016-04-20
      • 2019-09-23
      • 2016-02-13
      • 2016-08-03
      • 1970-01-01
      • 2018-11-28
      相关资源
      最近更新 更多