【问题标题】:Make _id index unique in a mongodb collection使 _id 索引在 mongodb 集合中唯一
【发布时间】:2017-01-26 10:03:11
【问题描述】:

我最近在 Mongo 2.6 副本集中看到了这个错误:

WARNING: the collection 'mydatabase.somecollection' lacks a unique index on _id. This index is needed for replication to function properly.

我假设 _id 索引默认是唯一的。但我正在尝试检查/设置它。 getIndexes 显示没有唯一的选项集。

> db.somecollection.getIndexes()[0]
{
        "v" : 1,
        "key" : {
                "_id" : 1
        },
        "ns" : "mydatabase.somecollection",
        "name" : "_id_"
}
> db.somecollection.ensureIndex({"_id":1},{unique:true})
> { "numIndexesBefore" : 3, "note" : "all indexes already exist", "ok" : 1 }
> db.somecollection.getIndexes()[0]
{
        "v" : 1,
        "key" : {
                "_id" : 1
        },
        "ns" : "mydatabase.somecollection",
        "name" : "_id_"
}

我试过.validate(true):

...
    "valid" : true,
    "errors" : [ ],
    "ok" : 1
}

还有.reIndex() 运行没有错误。我无法删除 _id 索引来重新创建它 - 如何将索引设置为唯一或我应该怎么做才能确保 RS 中的数据一致性?请注意,RS 已按照 2.2 --> 2.4 --> 2.6 的升级说明进行升级。我找到了这个MongoDB - Collection lacks a unique index on _id,但那里没有任何东西可以解决我的问题。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    我过去曾在复制集的新成员添加了不同的兼容版本时看到过这种情况。在副本集中的所有节点上运行 db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } ),如果有一个不同,请停止该节点上的复制,更改 CompatibilityVersion,然后将其准备好复制到副本。

    【讨论】:

      【解决方案2】:

      所以事实证明,当一个新成员被添加到现有副本集中时出现了错误,并且只显示在该成员上。如果我连接到数据库并尝试添加重复的_id,我会得到通常的E11000 duplicate key error index: ...,即使getIndexes() 没有指示索引的唯一约束(假设它是隐式的)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-25
        • 2012-03-24
        • 1970-01-01
        • 2019-02-23
        • 2014-03-19
        • 2021-06-07
        • 1970-01-01
        • 2023-03-06
        相关资源
        最近更新 更多