MongoDB唯一索引未起作用。

5

我正在使用Java连接Mongodb。

我会创建一个集合和一个索引,如下所示:

collection = mongoClient.getDB(DB_NAME).getCollection(COLLECTION_NAME)
collection.ensureIndex(new BasicDBObject(['customerReference': 1, 'unique': true]))

当我在Mongo shell中检查时,我看到:
{ 
   "v" : 1, 
   "key" : { "customerReference" : 1, "unique" : true }, 
   "ns" : "diagnostics.diagnosticData", 
    "name" : "customerReference_1_unique_" 
}

但是我仍然可以插入重复的数据:

{ 
  "_id" : ObjectId("52f3ba8a7d841c01680e0bc5"), 
  "customerReference" : 3, 
  "data" : "original data", 
  "created" : ISODate("2014-02-06T16:38:34.191Z") 
}
{ 
  "_id" : ObjectId("52f3ba8a7d841c01680e0bc6"), 
  "customerReference" : 3, 
  "data" : "duplicate data", 
  "created" : ISODate("2014-02-06T16:38:34.194Z") 
}

为什么?
2个回答

3
也许您没有正确创建索引。 请在DB shell中执行以下语句来完成创建:
db.refs.ensureIndex({customerReference: 1}, {unique : true})

在这里,当我尝试插入带有重复的customerReference的文档时,我会收到一个错误,内容如下:

E11000 重复键错误索引:test.refs.$customerReference_1 dup key: {:3.0}

当我执行db.refs.getIndexes()命令时,我会得到以下结果:

{
    "v" : 1,
    "key" : {
        "customerReference" : 1
     },
     "unique" : true,
     "ns" : "test.refs",
     "name" : "customerReference_1"
 }

这表明唯一索引已经正确创建,但与您的略有不同。

更新: 当您在集合中确保索引时,您只需要创建一个BasicDBObject,这将导致:

"key" : { "customerReference" : 1, "unique" : true }

在这里,key 的值不应包含 unique 属性。

unique 属性应该放置在 index 文档中,就像我的代码一样:

"key" : {
     "customerReference" : 1
 },
 "unique" : true

为了正确创建索引,您需要提供两个BasicDBObjects
  • 一个用于{customerReference : 1}
  • 一个用于{unique : true}

但是你可以看到它被创建了,因为我查询了索引集合。你能看出有什么问题吗? - FinalFive
是的,我现在看到了区别。索引的键不应该包括唯一字段。谢谢! - FinalFive

0

我正在使用JavaScript的mongoose,但我认为我发现的解决方案也适用于其他语言... 当您将数据库与应用程序连接时,请添加此选项:"audoIndex:true" 例如,在JS中,我们会这样做:

const options = {
// your options go here
...
// this code is the solution
audoIndex: true
}
mongoose.connect(DB_URI, options);

我也删除了出现问题的集合并重新创建它,以确保它能正常工作。 我在https://dev.to/emmysteven/solved-mongoose-unique-index-not-working-45d5找到了这个解决方案。 我还尝试了像“重启MongoDB”之类的解决方案,但对我没有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接