【问题标题】:Can IndexOptionsConflict be avoided to change expiredAfterSeconds in MongoDB index?可以避免 IndexOptionsConflict 更改 MongoDB 索引中的 expiredAfterSeconds 吗?
【发布时间】:2019-05-23 18:44:30
【问题描述】:

我可以通过这种方式在 mongo shell 中使用expiredAfterSecconds 创建索引:

db.x.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

我可以重新执行相同的命令,这对 mongo 来说没问题:

> db.x.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 2,
    "numIndexesAfter" : 2,
    "note" : "all indexes already exist",
    "ok" : 1
}

但是,如果我尝试更改 expiredAfterSecconds 值来重新创建我得到的索引并出错:

> db.x.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 7200 } )
{
    "ok" : 0,
    "errmsg" : "Index with name: createdAt_1 already exists with different options",
    "code" : 85,
    "codeName" : "IndexOptionsConflict"
}

如果我使用ensureIndex() 而不是createIndex(),也是一样。

据我所知,我发现修改expireAfterSeconds 值的唯一方法是删除索引,然后重新创建它,但我想知道是否还有其他方法(可能是某种“覆盖”选项要传递给createIndex()?)。

我正在使用 PyMongo,所以如果它可以解决 mongo shell 限制,那对我来说也很好。

【问题讨论】:

标签: mongodb pymongo mongodb-indexes


【解决方案1】:

截至mongo doc

  • 如果某个字段已经存在非 TTL 单字段索引,则无法在同一字段上创建 TTL 索引,因为您无法创建具有相同键规范且仅选项不同的索引。要将非 TTL 单字段索引更改为 TTL 索引,您必须先删除索引,然后使用 expireAfterSeconds 选项重新创建。
  • 您不能使用 createIndex() 更改现有索引的 expireAfterSeconds 值。而是将 collMod 数据库命令与索引集合标志结合使用。否则,要更改现有索引的选项值,必须先删除索引并重新创建。

更多关于使用collMod的信息是:here

正如comment 中提到的@adam-harrison,也请检查here

【讨论】:

  • 我不知道collMod。感谢您的参考!这似乎正是我需要的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多